如何重新路由MOQ呼叫?

时间:2016-02-14 02:46:43

标签: c# .net unit-testing mocking moq

尝试模拟以下界面,但发现语法真的很难处理。

public interface IKvpStoreRepository
{
    string this[string key] { get; set; }

    Task<bool> ContainsKey(string key);
}

现在我希望将值记录到后备存储中,如下所示:

var backingStore = new Dictionary<string,string>();
var mockKvpRepository = new Mock<IKvpStoreRepository>();
mockKvpRepository.
    Setup(_ => _[It.IsAny<string>()] = It.IsAny<Task<string>>()) //BROKE [1]
    .Callback((key,value) => backingStore[key] = value) //??? [2]
    .ReturnsAsync("blah"); //??? [3]

[1]表达式树可能不包含赋值。

[2]我如何同时获得关键和价值?

1 个答案:

答案 0 :(得分:1)

此测试通过。

[Test]
public void q35387809() {
    var backingStore = new Dictionary<string, string>();
    var mockKvpRepository = new Mock<IKvpStoreRepository>();

    mockKvpRepository.SetupSet(x => x["blah"] = It.IsAny<string>())
        .Callback((string name, string value) => { backingStore[name] = value; });

    mockKvpRepository.Object["blah"] = "foo";

    backingStore.Count.Should().Be(1);
    backingStore["blah"].Should().Be("foo");
}