【问题标题】:mock method expecting a list期望列表的模拟方法
【发布时间】:2020-04-24 09:38:18
【问题描述】:

我有一个需要字符串集合并且我想模拟的方法:

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

我想模拟对该方法的每次调用,该方法具有包含以下项目的任何集合:["DLKM"],无论集合的类型是数组还是列表或其他。

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

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

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

这是我的模拟:

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】:

    不要将匹配器放入单个变量中,只需将代码提取到您在每个模拟中调用的方法中:

    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());
    }
    

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-12-09
      • 2016-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多