Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Faking a generic method FakeItEasy

Tags:

c#

fakeiteasy

How would you go about faking the following:

public interface IBlah
{
    Func<T, bool> ApplyFilter<T>(Func<T, bool> predicate) where T:IMessage;
}

What I would like is for the fake to simply return it's argument without any changes. However, I would like to verify that the fake has been called exactly once. A use case is given below:

  public class Something
  {

     public Something(IBlah blah) { _blah = blah; }

     public bool DoSomething(SomeValue m, Func<SomeValue, bool> predicate)
     {
         Func<SomeValue, bool> handler = _blah.ApplyFilter(predicate);
         return handler(m);
     }
  }

i.e. the fake needs to act as a pass through but I also need to be able to verify it's been used.

What's the best way to go about this?

[Please don't worry about the contrived example...there's a lot of things going on under the covers, but I've simplified it down to the example above.]

like image 489
ashic Avatar asked Nov 03 '22 05:11

ashic


1 Answers

Would this solve your issue? It will pass through the predicate and also verify that ApplyFilter was called exactly once

    [Fact]
    public void TestFeature()
    {
        var fake = A.Fake<IBlah>();
        A.CallTo(() => fake.ApplyFilter(A<Func<int, bool>>.Ignored)).ReturnsLazily(x =>
            {
                return x.GetArgument<Func<int, bool>>("predicate");
            });
        var something = new Something(fake);
        var result = something.DoSomething(1, x => x > 1);

        Assert.False(result);
        A.CallTo(() => fake.ApplyFilter(A<Func<int, bool>>.Ignored)).MustHaveHappened(Repeated.Exactly.Once);
    }
like image 98
cecilphillip Avatar answered Nov 08 '22 10:11

cecilphillip