拟态方法,期待一个列表

问题描述 投票:0回答:1

我有一个方法,它需要一个字符串的集合,我想对它进行模拟。

bool DoSomething(IEnumerable<string> myList) { ... }

我想模拟每一个对该方法的调用 有以下项目的集合: ["DLKM"]不管这个集合的类型是数组还是列表之类的东西

因此,我使用 NSubstitute 创建了一个参数匹配器。

var modellarten = Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any());

这将匹配任何只包含字符串的字符串集合。"DLKM".

这是我的mock。

var mock = Substitute.For<IMyInterface>();
mock.DoSomething(modellarten).Returns(true);

然而,当我使用同一个arg-matcher来模拟多个方法的时候,调用到 DoSomething 返回默认值 false:

var mock = Substitute.For<IMyInterface>();
mock.Init(modellarten).Returns(true);
mock.DoSomething(modellarten).Returns(true);

所以我想这和匹配器的闭包有关。但我不知道如何在不重复代码的情况下模拟这两个方法。modellarten:

var mock = Substitute.For<IMyInterface>();
mock.Init(Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any())).Returns(true);
mock.DoSomething(Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any())).Returns(true);
c# unit-testing mocking nsubstitute
1个回答
0
投票

与其把匹配器放到一个单独的变量中,不如把代码提取到每次模拟调用的方法中。

IMyInterface MockInterface()
{
    var mock = Substitute.For<IMyInterface>();
    mock.Init(MatchCollection()).Returns(true);
    mock.DoSomething(MatchCollection()).Returns(true);
    return mock;
}
IEnumerable<string> MatchCollection() 
{
    return Arg.Is<IEnumerable<string>>(x => !new[] { "DLKM" }.Except(x).Any());
}

这将在每次调用时创建一个新的匹配器,而不是使用之前创建的匹配器。

© www.soinside.com 2019 - 2024. All rights reserved.