FakeItEasy - Is it possible to intercept a method and replace it with my own implementation?
Asked Answered
O

2

9

I have the following interface :

public interface IOuputDestination
{
    void Write(String s);
}

In my unit test, I mock it like so :

var outputDestination = A.Fake<IOutputDestination>();

What I want to do, is intercept the Write method so that it uses my custom implementation that I define in my test. Something like this :

String output = "";
A.CallTo(() => outputDestination.Write(A<String>.Ignored)).Action(s => output += s);
              //Is something like this even possible ? ----^

Here the Action method does not exist, but what I would like to happen is that any parameter passed into outputDestination.Write be redirected to my custom action. Is this possible using FakeItEasy? If not, is there another mocking framework that allows this kind of behavior?

Olga answered 19/10, 2012 at 18:51 Comment(0)
W
10

You can get that behavior with Invokes:

String output = "";
A.CallTo(() => outputDestination.Write(A<String>.Ignored))
    .Invokes((string s) => output += s);
Wallack answered 19/10, 2012 at 19:23 Comment(0)
M
0

You don't really show how you're using outputDestination once you've created it. Would you be injecting it into some method under test? If so, then What if, instead of creating a fake, you create a specially crafted class that implements IOutputDestination and which contains your required implementation of Write()?

I guess this would depend what (if any) other bahaviours you need to verify on your fake. Its hard to know without more context.

Modest answered 27/12, 2012 at 14:20 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.