Giter Site home page Giter Site logo

fakeiteasy / fakeiteasy Goto Github PK

View Code? Open in Web Editor NEW
1.6K 51.0 178.0 23.32 MB

The easy mocking library for .NET

Home Page: https://fakeiteasy.github.io

License: MIT License

C# 99.58% Batchfile 0.02% Shell 0.01% Visual Basic .NET 0.38% PowerShell 0.01% F# 0.01%
mocking fake-objects dotnet dotnet-core hacktoberfest

fakeiteasy's Introduction

Are you mocking me?

NuGet version Build status

A .NET dynamic fake library for creating all types of fake objects, mocks, stubs etc.

  • Easier semantics, all fake objects are just that - fakes - the use of the fakes determines whether they're mocks or stubs.
  • Context-aware fluent interface guides the developer.
  • Designed for ease of use.
  • Full compatibility with both C# and VB.Net.

Faking amazing example

// Creating a fake object is very easy!
// No mocks, or stubs; everything's a fake.
var shop = A.Fake<ICandyShop>();

// Easily set up a call to return a value.
var lollipop = new Lollipop();
A.CallTo(() => shop.GetTopSellingCandy()).Returns(lollipop);

// Exercise your system under test by using the fake as you
// would an instance of the faked type.
var customer = new SweetTooth();
customer.BuyTastiestCandy(shop);

// Asserting uses the same syntax as configuring calls.
A.CallTo(() => shop.BuyCandy(lollipop)).MustHaveHappened();

Resources


FakeItEasy logo designed by Vanja Pakaski.

fakeiteasy's People

Contributors

adamralph avatar akrock avatar andreycha avatar ar7z1 avatar asgerhallas avatar blairconrad avatar chillitom avatar chrismatheson avatar claudiobernasconi avatar danieljwest avatar danielmarbach avatar dashue avatar dependabot[bot] avatar dozed avatar galaktor avatar jeremymeng avatar jimmyheaddon avatar jszumigaj avatar martinskuta avatar medmondson avatar mvas avatar natiki avatar patrik-hagne avatar philippdolder avatar piotrklecha avatar rmkrs avatar sguldmund avatar thomaslevesque avatar ulrichb avatar vanillajonathan avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

fakeiteasy's Issues

remove old branches

All old branches which have been merged into master probably ought to be removed.

Or does anyone want to keep them for any reason?

Automatically build pull requests

The easiest way to do this is by using https://travis-ci.org which has this built in. We'd need to be building for Mono since their build environment currently only consists of Linux machines. I think it would also be easiest if we used Rake.

This can also be done on TeamCity, see http://hadihariri.com/2013/02/06/automatically-building-pull-requests-from-github-with-teamcity/

For now, let's go with TeamCity. We can think about using Travis CI later if we either start to build for Mono or if Travis CI starts to provide Windows builds.

Verification with ByRef parameters fails when reference is modified

When passing an argument to a method which uses a ByRef (VB.NET) parameter, verification of this parameter fails when the value of the argument changes.

Public Interface ISomething

  Sub DoSomething(ByRef io_oSomething As Foo)

End Interface

<TestClass()>
Public Class UnitTest1

  <TestMethod()>
  Public Sub TestSomethingFails()
    Dim oFoo As New Foo

    Dim oFake As ISomething = A.Fake(Of ISomething)()

    oFoo.Id = 1
    oFake.DoSomething(oFoo)
    oFoo.Id = 2
    oFake.DoSomething(oFoo)

    A.CallTo(Sub() oFake.DoSomething(A(Of Foo).That.Matches(Function(foo As Foo) foo.Id = 1))).MustHaveHappened()

  End Sub

  <TestMethod()>
  Public Sub TestSomethingSucceeds()
    Dim oFoo As New Foo(1)

    Dim oFake As ISomething = A.Fake(Of ISomething)()

    oFoo.Id = 1
    oFake.DoSomething(oFoo)
    oFoo.Id = 2
    oFake.DoSomething(oFoo)

    A.CallTo(Sub() oFake.DoSomething(A(Of Foo).That.Matches(Function(foo As Foo) foo.Id = 2))).MustHaveHappened(Repeated.Exactly.Twice)

  End Sub

  <TestMethod()>
  Public Sub TestSomethingFailsToo()
    Dim oFoo As New Foo(1)

    Dim oFake As ISomething = A.Fake(Of ISomething)()

    oFoo.Id = 1
    oFake.DoSomething(oFoo)
    oFoo.Id = 2

    A.CallTo(Sub() oFake.DoSomething(A(Of Foo).That.Matches(Function(foo As Foo) foo.Id = 1))).MustHaveHappened()

  End Sub

  <TestMethod()>
  Public Sub TestSomethingSucceedsToo()
    Dim oFoo As New Foo(1)

    Dim oFake As ISomething = A.Fake(Of ISomething)()

    oFoo.Id = 1
    oFake.DoSomething(oFoo)

    A.CallTo(Sub() oFake.DoSomething(A(Of Foo).That.Matches(Function(foo As Foo) foo.Id = 1))).MustHaveHappened()

  End Sub

End Class

NuGet pack output folder is wrong if version.txt has a line ending

I had the clever idea of updating Version.txt directly via the GitHub website in master and inadvertently added a line ending which propagated to the nuget pack command line, as can be seen from the build log http://teamcity.codebetter.com/viewLog.html?tab=buildLog&buildTypeId=bt929&buildId=67143

Just in case a line ending ever ends up in Version.txt again, we need to make rakefile.rb immune to it. It's probably a good idea to first split on line ending chars and use the first token for further operations.

FYI trying to remove the line ending via the GitHub website did not work. It resulted in a no-change commit. Note to self: never use the GitHub website to commit to master again, ever.

normalise and enforce correct line endings

See https://help.github.com/articles/dealing-with-line-endings

I've still seen a few files cropping up with mixed line endings even when using autocrlf=true, which is strange.

I think if we do a one-off normalisation and enforcement using gitattributes then we should kill this problem once and for all.

Note that we need to run a one-off build on the build server with 'clean all files in checkout directory before build' switched on after making this change.

Adopt Semantic Versioning 2.0.0-rc.1

http://semver.org/

Main points:

  1. drop the fourth element from the version scheme
  2. increment major when making breaking change, resetting minor to zero
  3. increment minor for all other releases, resetting patch to zero
  4. increment patch only when fixing a bug

Raise Non-EventArgs events

The Raise<>.With syntax is typed to events with the EventArgs convention.

There are many cases where I use events with custom delegate types, like such

public delegate void MyDelegate(MyCargo c);
// ...
public event MyDelegate Foo;

Unfortunately I cannot raise such an event on a Fake with the given Raise<> API.

A way to raise any type of delegate/cargo would be very useful; meaning if Raise<> took a custom/generic delegate signature and didn't force the (sender,EventArgs) pattern.

The use case I imagine (or, really, expected at first) was this (continuing the above delegate example):

var f = A.Fake<IFireEvents>();

f.Foo += Raise.With<MyDelegate>(new Cargo()).Now;

or maybe

f.Foo += Raise.With<MyCargo>(new Cargo()).Now;

where, in the latter case, Raise would expose an Action<TCargo> or similar.

Not sure how much of this is really possible, but depending on how desperate I get I might try to hack it up myself in a fork.
However, I'm sure you guys know what to do in this case much better than I do :-)

Thanks for the great tool!

No way to assert a call to a setter wasnt made.

Big fan of framework, found a small annoyance:

I'd like to assert that a property setter was not called. I'm looking at your documentation, and I cant find a way to do this.

        private class IntBox
        {
            public int IntProperty { get; set; }
        }

        [Test]
        public void when_using_A_callTo_on_a_property_set_call()
        {
            var fake = A.Fake<IntBox>();
            fake.IntProperty = 4;

            A.CallTo(() => fake.IntProperty).WithAnyArguments().MustNotHaveHappened();
            //ahhh so set calls are excluded...

//            A.CallTo(() => fake.IntProperty = -1).WithAnyArguments().MustHaveHappened();
            //and of course an expression cannot contain an assignment operator...
        }

I would argue that the expected behavior is that

A.CallTo(() => fake.IntProperty).MustNotHaveHappened()

would check for both get and set calls, but this would be a breaking change in your framework and might anger a good number of people, so perhaps the simple static methods Get and Set on IReturnValueArgumentValidationConfiguration<T> would suffice, so that my assertion could be:

A.CallTo.Get(() => fake.IntProperty).MustNotHaveHappened()
A.CallTo.Set(() => fake.IntProperty).MustNotHaveHappened()

Cheers!

-Geoff

Fakes can't be serialized in the IL-merged version

The below example fails with the following error message:

Attempt by method 'Castle.Proxies.PersonProxy.GetObjectData(System.Runtime.Serialization.SerializationInfo, System.Runtime.Serialization.StreamingContext)' to access method 'Castle.DynamicProxy.Generators.Emitters.TypeUtil.Sort(System.Reflection.MemberInfo[])' failed.

 class Program
{
    static void Main(string[] args)
    {
        var person = A.Fake<Person>();

        var formatter = new BinaryFormatter();
        using (var stream = new MemoryStream())
        {
            formatter.Serialize(stream, person);
        }

    }
}

[Serializable]
public class Person
{}

There are tests that asserts that fakes can be serialized so this must have to do with the IL-merge.


Will be released as patch 1.9.1.

  • change version.txt to patch version
  • nuspec - update releaseNotes
  • push to upstream branch, check build
  • push nuget package
  • add tag to commit, push to upstream branch
  • create PR to upstream master, check build, merge PR, check build, delete branch
  • tweet ;-)

1.9 release

Ready when all other issues forming part of the release are Done.

  • change version.txt
  • nuspec - update releaseNotes (omit parentheses from issue URLs - looks ugly - use a dash instead)
  • nuspec - update projectURL
  • push nuget package
  • add tag to commit
  • tweet ;-)

intermittent error executing Rules_should_only_be_valid_within_the_current_scope

I noticed this first on the build server in this build http://teamcity.codebetter.com/viewLog.html?buildId=64653&tab=buildResultsDiv&buildTypeId=bt483

The next build succeeded (with no changes) so I suspected an intermittent bug. I then tried running the test repeatedly in Visual Studio using TestDriven.NET and sure enough, after about 10 executions I got

Test 'FakeItEasy.Tests.Core.FakeManagerTests.Rules_should_only_be_valid_within_the_current_scope' failed: System.NullReferenceException : Object reference not set to an instance of an object.
Core\FakeManagerTests.cs(281,0): at FakeItEasy.Tests.Core.FakeManagerTests.Rules_should_only_be_valid_within_the_current_scope()

Drop support for Silverlight 3

I want so see how much (if any) objection there is to this.

Silverlight 3 is not supported in Visual Studio 2012. This means continued support for SL3 puts an extra burden on developers to maintain an installation of an obsolete IDE (VS2010).

New Castle.Windsor Version

I'm still experiencing problems when updating Castle.Windsor. Are there considerations about il-merging the specific Castle version into FakeItEasy? Or what would be the best solution if i want to keep my Castle version up to date?

Throws should be lazy

The interface IExceptionThrowerConfiguration has a method "Throws", this should instead be "ThrowsLazily" that takes a Func. The current Throws method should be an extension method for this interface instead.

FakeItEasy and "params" args

I have a method with the following signature.

Foo GetFooById( int id, params string[] children )

This method is defined on an interface named IDal.

In my unit test I write the following:

IDal dal = A.Fake<IDal>();

Foo fooToReturn = new Foo();
fooToReturn.Id = 7;

A.CallTo(()=>dal.GetFooById(7, "SomeChild")).Returns(fooToReturn);

When the test runs, the signature isn't being matched on the second argument. I tried changing it to:

A.CallTo(()=>dal.GetFooById(7, new string[]{"SomeChild"})).Returns(fooToReturn);

But that was also unsuccessful. The only way I can get this to work is to either ignore the second argument:

A.CallTo(()=>dal.GetFooById(7, A<string[]>.Ignored )).Returns(fooToReturn);

Or to use IsSameSequenceAs:

A.CallTo(()=>dal.GetFooById(7, A<string[]>.That.IsSameSequenceAs(new string[] { "SomeChild" }) )).Returns(fooToReturn);

The latter works, but is a little long and unwieldly.

If FakeItEasy could handle params arguments more naturally (like the framework does) it would make this type of situation more intuitive.

Events can't have more than one subscriber.

If you have 2 different event handlers subscribed to the same event, when you raise the event using something like the following:

    foo.SomethingHappened += Raise.With(EventArgs.Empty).Now;

.. the event handler you subscribed last will be called twice rather than each handler being called once.

FakeItEasy.FluentAssertions package

Maybe this is too much overhead for a simple benefit but I'm dumping it here anyway as an idea. Just thought it might be cool to support fluent assertions which would allow to use their exception and assertion model. The one could use:

A.CallTo().Should().HaveHappened().And.ExactlyOnce()

This would also help to spread the usage of FluentAssertions

Provide an external XML annotations file to prevent ReSharper's "implicit captures" warning

Please see this blog post: http://www.hmemcpy.com/blog/2013/02/preventing-resharpers-implicitly-captured-closure-warning-in-fakeiteasy-unit-tests/

ReSharper will complain about the A.CallTo methods, that they implicitly capture local variables. It's possible to prevent this, by teaching ReSharper (via external annotations, so it's completely seamless non-intrusive) that the lambdas are executed immediately by FakeItEasy.

By supplying an external annotations XML together with the DLL, this will "just work", and no code changes required anywhere.

Address StyleCop warnings

Either by fixing issues, or changing the analysis settings in each case. Preferably the former, we should try and stick to the default StyleCop settings as much as possible so that we adopt a coding style which is more compatible with other projects.

Once this is done, we should add <StyleCopTreatErrorsAsWarnings>false</StyleCopTreatErrorsAsWarnings> to the properties in the csproj files so that the build fails on violations.

1.10.0-beta03 release

In order to include patch 1.9.1 #74

  • change version.txt to beta version
  • push to origin branch, create PR to upstream master, check build, merge PR, check build, delete branch
  • push nuget package
  • add tag to commit in master, push to upstream

MissingMethodException - Cannot create an instance of an interface when calling A.Fake<ITest> when debugging

when I debug MSUnit test code I get

System.MissingMethodException occurred
  Message=Cannot create an instance of an interface.
  Source=mscorlib
  StackTrace:
       at System.RuntimeTypeHandle.CreateInstance(RuntimeType type, Boolean publicOnly, Boolean noCheck, Boolean& canBeCached, RuntimeMethodHandleInternal& ctor, Boolean& bNeedSecurityCheck)
       at System.RuntimeType.CreateInstanceSlow(Boolean publicOnly, Boolean skipCheckThis, Boolean fillCache)
  InnerException: 

on the first A.Fake<ITest>() call

ITest tt = A.Fake<ITest>();

It runs normally when I just run tests. so it happens only under visual studio debugger. what is is missing?

windows7/VS2010 ultimate/FakeItEasy 1.7.4626.65
Started recently... not sure what changed.

add CONTRIBUTING.md

with guideline for contributors, e.g line endings, branching, etc.

This is a special file that GitHub knows about and the UI tells fork creators about it.

Remove package dependency on Castle.Core

Hello,

I'm a long time fan of FakeItEasy, but one thing always bothered me about its NuGet package, and that's the fact that Castle.Core is being downloaded as a separate, external dependency.

I believe Patrick mentioned on twitter once that this is what NuGet is for - managing dependencies. And while I agree, in my opinion Castle.Core is an implementation detail of FakeItEasy. What happens if there's an older/newer version of Castle.Core already in my project? Potentially, this might break FakeItEasy.

I propose ILMerging Castle.Core directly into FakeItEasy, and simplify deployment. I believe this was done in the standalone download, before NuGet.

Thanks!

Igal.

If one interface implements another interface and both contains the same property the property is not set on the original object that implements the first interface

What steps will reproduce the problem?

  1. See code below
  2. var myFake = A.Fake<IMyInterface>();
  3. Send to SetValues(myFake) on SomeClass
  4. check "Number"-value on myFake, it is null
  5. cast myFake to IYourInterface, and check "Number"-value the value is 0.

What is the expected output? What do you see instead?
That the value on MyFake to be 0 not null.

What version of the product are you using? On what operating system?
Tried on version 1.7.4257.42 (other: c# / windows 7 / visual studio 2010 ultimate)

Please provide any additional information below.

Code:

public interface IMyInterface : IYourInterface
{
   decimal? Number { get; set; }
}

public interface IYourInterface
{
   decimal? Number { get; set; }
}

public class SomeClass
{
   public void SetValues(IYourInterface yi)
   {
      yi.Number = 0;
   }
}

Address compiler warnings

Currently 10 inside VS and 6 outside.

Address warnings and then set all projects to treat all warnings as errors.

Address code analysis warnings

The core FakeItEasy project has 74 warnings. Other projects may also have further warnings.

In each case we should fix the code or suppress the warning, whichever is appropriate.

We should also consider our policy for running code analysis as part of the build. The issue here is speed. Code analysis can really slow the build down. If we do choose to run code analysis as part of the build, it should fail when there are warnings, as mentioned by @philippdolder (#36 (comment)).

  • switch to FakeItEasy ruleset
  • address warnings
  • switch all warnings to errors
  • switch on analysis for all release builds (if desired)

Automated build

There should be a way easier way to build a new version of FakeItEasy than there is today.

The output of the build should be the following:

A zip-archive containing:

  • License.txt
  • Merged version of FakeItEasy.dll (FakeItEasy together with Castle.Core).
  • Non merged version of both FakeItEasy.dll and Castle.Core.dll
  • The dlls mentioned above compiled both for .Net 3.5 and .Net 4.0
  • The dlls mentioned above both signed (using the key file Source/FakeItEasy/FakeItEasy.snk) and non signed.
  • Silverlight versions (3.5, 4.0, signed and non signed, merged and non merged).

There should be two NuGet packages produced, one for the signed version and one for the non signed version.

It would be great if a release build and push could be triggered by setting a tag in git on a release branch. The tag should be the version number that should be used for the build.

There is a TeamCity account set up at http://teamcity.codebetter.com/project.html?projectId=project152

UPDATE

We've decided that initially we will just produce a signed NuGet so we can get this closed out with merging/non-merging as a separate concern in #16. If we feel we need other outputs, e.g. signed/non-signed, merged/non-merged, etc. then we can raise further issue(s).

UPDATE

As part of closing this, assuming we have consolidated down to a single build config, which should switch on the 'Report change status to GitHub' build feature as detailed at http://hadihariri.com/2013/02/06/automatically-building-pull-requests-from-github-with-teamcity/

Currently we can't use this build feature because the 3 different build configs interfere with each other, i.e. the build might pass on one and fail on another and then it's a case of most recent wins with the status update on the pull request.

WhenArgumentsMatch executes before Where

http://code.google.com/p/fakeiteasy/issues/detail?id=14

The folowing code generate an exception :

public interface ISetOnly
{
    int MyProperty { set; }

    bool MyProperty2 {set;}
}

[Test]
public void MyProperty_CanBeVerified()
{
    var setOnly = A.Fake<ISetOnly>();

    setOnly.MyProperty = 1;
    setOnly.MyProperty2 = false;

    A.CallTo(setOnly).Where(x => x.Method.Name == "set_MyProperty")
        .WhenArgumentsMatch(x => x.Get<int>(0) == 1).MustHaveHappened();
}

It looks like filtering with "Where(x => x.Method.Name ...)" doesn't work.

Cannot install?

Attempting to resolve dependency 'Castle.Core (โ‰ฅ 3.1.0.0)'.
Successfully installed 'Castle.Core 3.1.0'.
Successfully installed 'FakeItEasy 1.7.4626.65'.
The process cannot access the file 'C:\Project\Castle.Core.3.1.0\lib\net40-client\Castle.Core.dll' because it is being used by another process.
The directory is not empty.

Successfully uninstalled 'Castle.Core 3.1.0'.
Install failed. Rolling back...
Failed to add reference to 'Castle.Core'.

Keep getting this message when installing FakeItEasy, also same error when installing Castle.Core, maybe this should be sent to castle.Core but thought you might want to know...

Improve parameter matching and assignment for ref parameters

In Rhino Mocks, there is a way to specify a dummy ref parameter like so:

ref Arg<string>.Ref(Rhino.Mocks.Constraints.Is.Equal(string.Empty), "New value").Dummy

While I generally dislike ref parameters (especially for unit test purposes), there is no way around legacy APIs or third-party code.

What do you think about this syntax:

ref A<string>.That.IsEqualTo(string.Empty).ChangesTo("New value").Dummy

// extension method signature
public static Dummy<T> ChangesTo<T>(this T value, T newValue);

// class
public class Dummy<T>
{
    public T Dummy;
}

This obviously is a draft and will require a bit of polishing...

Incorrect exception message when ReturnLazily signature does not match

var foo = A.Fake<IFoo>();
A.CallTo(() => foo.Baz()).ReturnsLazily((object fake, object arg) => 0);
foo.Baz();

throws an exception with the message

The faked method has the signature (), but invokes was used with (System.Object, System.Object).

The exception message should be

The faked method has the signature (), but returns lazily was used with (System.Object, System.Object).

1.10 release

Ready when all other issues forming part of the release are Done.

  • change version.txt to stable version
  • nuspec - update releaseNotes
  • nuspec - add iconUrl to a 128x128 PNG of 'the old ladies' (optional, if we have time)
  • push to origin branch, create PR to upstream master, check build, merge PR, check build, delete branch
  • push nuget package
  • add tag to commit in master, push to upstream
  • change version.txt to next beta version
  • nuspec - change release notes to TBD
  • push to origin branch, create PR to upstream master, check build, merge PR, check build, delete branch
  • create new issue based on this one for next release
  • tweet ;-)

Support parallel test execution

Parallel test execution is not currently supported.
If it turned on, ExpectationException (Call to non configured method) errors appear :(

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.