How to test whether a Func<T> has been called using the FakeItEasy framework?
Asked Answered
S

2

6

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();
Squashy answered 5/12, 2013 at 12:2 Comment(1)
If FakeItEasy is anything like other mocking frameworks then 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. You can't just invoke a random delegate and check it was called.Bogus
M
7

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();
}
Mcginn answered 5/12, 2013 at 12:22 Comment(0)
B
1

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);
Bogus answered 5/12, 2013 at 12:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.