c# - NSubstitute 错误 UnexpectedArgumentMatcherException

标签 c# mocking nsubstitute

我收到以下错误:

NSubstitute.Exceptions.UnexpectedArgumentMatcherException: 'Argument matchers (Arg.Is, Arg.Any) should only be used in place of member arguments. Do not use in a Returns() statement or anywhere else outside of a member call. Correct use:
sub.MyMethod(Arg.Any()).Returns("hi") Incorrect use:
sub.MyMethod("hi").Returns(Arg.Any())'

当尝试模拟出以下界面时:

public interface IMyDate
{
    DateTime GetDate();
}

这是我 mock 它的地方:

var myDate = Substitute.For<IMyDate>();
myDate.GetDate().Returns(testDate); // Error thrown here

谁能解释一下我做错了什么?

var myDate = Substitute.For<IMyDate>();
myDate.GetDate().Returns(new DateTime(2018, 04, 05)); // Error thrown here

给出相同的结果。

最佳答案

这可能是由于较早的测试存在问题。参见 this answer有关跟踪此问题的一些步骤。我在下面包含了该答案的快照:

This is most like due to a previous test using an argument matcher against a non-virtual method, or in a Returns statement.

Unfortunately this can be quite tricky to debug. First step is to see if the problem occurs when you run all the test in this fixture. If so, check all uses of Arg.Is|Any in that fixture, starting with the one that runs immediately before the test that fails (if your test framework uses a predictable test order, otherwise you'll need to look at test logs to see what tests proceed the failing one).

If it does not occur with that fixture you'll need to look through the fixtures that run beforehand to see where the left over arg matcher is coming from. It is most likely somewhere near the failing test.

希望这对您有所帮助。好消息是,下一个 NSubstitute 版本 (v4) 将在这些情况下提供更多帮助。

另请参阅:How not to use argument matchers .

关于c# - NSubstitute 错误 UnexpectedArgumentMatcherException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49669935/

相关文章:

c# - 如何更改 FlowDocumentReader 中选定文本的选择背景颜色

c# - 非程序员需要多长时间才能学习 C#、.NET Framework 和 SQL?

c# - Lambda 查询不适用于 `Task<IEnumerable<dynamic>>` 返回类型方法的 Moq 数据

c# - 如何通过NSubstitute中的父类(super class)匹配参数来 stub 方法?

VS2005 中的 C# : what do the following types default to in C#?

c# - 在运行时动态更新 WCF 路由服务配置

java - 不要模拟值对象 : too generic rule without explanation

java - 模拟策略

c# - NSubstitute - 测试特定的 linq 表达式