How to check whether a Func has been called using the FakeItEasy framework?

Example:

Func<bool> myFunc = () => true;

// Unfortunately this fails:
A.CallTo(myFunc.Invoke()).MustHaveHappened();
有帮助吗?

解决方案

You can do this assuming you are providing the Func to the code under test. You just make a Fake out of it like you would any other type.
It will look something like this.

public class Foo {
  public bool Bar(Func<bool> fn) {
    return fn();
  }
}

[Test]
public void Should_call_fn() {
  var fn = A.Fake<Func<bool>>();

  (new Foo()).Bar(fn);

  A.CallTo(() => fn.Invoke()).MustHaveHappened();
}

其他提示

I don' think you can do that. You can only determine if a Property/Method on an interface or virtual method on an abstract class is called, because you will have to mock this object and intercept calls to the method. You can't just invoke a random delegate and check it was called.

For example, if you have:

interface ISomething
{
    void SomeMethod();
}

then you can do:

var fake = A.Fake<IContactSubmitter>();

// code which passes fake as dependency to something so SomeMethod will be caled...

A.CallTo(() => fake.SomeMethod().MustHaveHappened(Repeated.Once.Exactly);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top