How to get access to parameters value in Returns() using FakeItEasy?
Asked Answered
A

2

33

I have an interface to a factory used to create some data objects.

interface IFactory
{
    IData Create (string name, string data);
}

interface IData
{
    // ....
}

class Data : IData
{
    public Data (string name, string data)
    {
        // .....
    }
}

I need to create a mock factory to pass to another module and this module will use this mock to create data.

For a quick example, a simple module looks like:

class QuickModule
{
    private readonly IFactory _factory;

    public QuickModule (IFactory factory)
    {
        _factory = factory;
    }

    public IEnumerable<IData> GetData ()
    {
        yield return _factory.Create ("name1", "abc");
        yield return _factory.Create ("name2", "def");
    }
}

So, the factory is called two times with two sets of parameters.

Using Moq, this is easy:

var factoryMock = new Mock<IFactory> ();
factoryMock.Setup (x => x.Create (It.IsAny<string> (), It.IsAny<string> ()))
                    .Returns ((string name, string data) => new Data (name, data));
var module = new QuickModule (factoryMock.Object);
var list = module.GetData ();

However using FakeItEasy this would not seem to be possible:

var factory = A.Fake<IFactory> ();
A.CallTo (() => factory.Create (A<string>.Ignored, A<string>.Ignored))
              .Returns (new Data (???, ???));
var module = new QuickModule (factory);
var list = module.GetData ();

How can I access the parameters values?

Aligarh answered 6/11, 2012 at 17:12 Comment(0)
A
58

Ok, it would seem that ReturnsLazily() is the answer.

So here's what I did:

var factory = A.Fake<IFactory> ();
A.CallTo (() => factory.Create (A<string>.Ignored, A<string>.Ignored))
              .ReturnsLazily ((string name, string data) => new Data (name, data));
var module = new QuickModule (factory);
var list = module.GetData ();

Is this the recommended way or is there another?

Aligarh answered 6/11, 2012 at 17:29 Comment(1)
This is the recommended way!Cashman
G
5

Here's how to return the object that you passed into the method.

ManufacturedPart inputPart;

A.CallTo(() => partRepo.InsertPart(A<ManufacturedPart>._))
  .ReturnsLazily(x => inputPart = x.Arguments.Get<ManufacturedPart>("part"));
Grissom answered 9/6, 2017 at 22:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.