简体   繁体   中英

How can I redirect arguments using NSubstitute

I am in the process of converting some test objects from RhinoMocks to NSubstitute and am having trouble setting up my mock repository.

See the following unit test code below:

[SetUp]
public void SetUp()
{
    _converter = Substitute.For<IStatisticsConverter>();
    _repository = Substitute.For<IRepository>();
    _updater = new StatisticsUpdater(_converter, null, _repository);
}

[Test]
public void CreateFrom_NoExistingItem_NewItemWithStatistics()
{
        var statisticsLog = new StatisticsLog();
        var statistics = new Statistics();

        _converter.ConvertToStatistics(statisticsLog).Returns(statistics);

        _repository.When(x => x.SaveStatistics(Arg.Any<Item>(), statistics))
            .Do(x => UpdateItem(?????,statistics));

        var actualItem = _updater.CreateFrom(statisticsLog);

        Assert.IsNotNull(actualItem);
        Assert.AreEqual(1, actualItem.Statistics.Count(), "number of statistics entries");
        Assert.AreSame(statistics, actualItem.Statistics.First(), "expected statistics");
}

private void UpdateItem(Item item, Statistics statistics)
{  
    item.AddStatistics(statistics);   
}

The test throws an error at Assert.AreEqual : "Expected 1 and Actual is 0."

What happens is, _updater is the System Under Test. The CreateFrom() function creates a new Item() and then internally calls Update(statisticsLog) . StatisticsLog is an XML file.

public Item CreateFrom(T deserializedEntity)
{
    Item = new Item();

    Update(deserializedEntity);

    return Item;
}

Once the file is parsed in the real updater, it gets saved to a database which is attached to the new Item (which was also added to the database as it did not exist before).

Now, the problem is, I need to get this newed Item and pass it into UpdateItem() which mocks the functionality of adding to the database. It adds the Statistics to the Item.Statistics list.

So - is there a way I can pull out this argument from the mocked Repository and pass it into UpdateItem ?

I managed to solve it :) Reference came from this thread here with a similar issue. Arg.Do()

 _repository.When(
    x => x.SaveStatistics(Arg.Any<Item>(), statistics)).Do(
        call =>
            {
                itemUsed = call.Arg<Item>();
                UpdateItem(itemUsed, statistics);
            });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM