如何使用正确的操作选项编写测试AutoMapper的测试

时间:2017-12-13 11:23:03

标签: c# unit-testing lambda automapper nsubstitute

我有这段代码,想测试opts.Items["foo"]设置是否正确。

public Result DoStuff(MyInput myObj)
{
    var mapped = _mapper.Map<Result>(myObj,
        opts =>
        {
            opts.Items["foo"] = "bar";
        });
    return mapped;
} 

我的测试看起来像这样

public void MapperShouldBeCalledWithCorrectOperationItems()
{
    // Arrange
    var optObj = Substitute.For<IMappingOperationOptions>();
    Action<IMappingOperationOptions> argumentUsed = null;
    _mapper.Received().Map<Result>(result, Arg.Do<Action<IMappingOperationOptions>>(arg => argumentUsed = arg));

    // Act
    _uut.DoStuff(new MyInput());
    argumentUsed.Invoke(optObj);

    // Assert
    optObj.Items["foo"].Should().Be("bar");
}

现在这不起作用,我甚至不确定我是否走在正确的道路上:(

我认为我不能检查lambda,所以我必须检查IMappingOperationOptions是否设置了Items["foo"]

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

我明白了!

public void MapperShouldBeCalledWithCorrectOperationItems()
{
    // Arrange
    var optObj = Substitute.For<IMappingOperationOptions>();

    Action<IMappingOperationOptions> argumentUsed = null;
    _mapper
        .Map<Result>(Arg.Any<Result>,
                     Arg.Do<Action<IMappingOperationOptions>>(arg => argumentUsed = arg));

    // Act
    _uut.DoStuff(new MyInput());
    argumentUsed.Invoke(optObj);

    // Assert
    optObj.Items["foo"].Should().Be("bar");
}