سؤال

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?

هل كانت مفيدة؟

المحلول

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?

نصائح أخرى

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"));
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top