10 c# mocking nsubstitute
I'm getting the following error:
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())'
When trying to mock out the following interface:
public interface IMyDate
{
DateTime GetDate();
}
Run Code Online (Sandbox Code Playgroud)
Here's where I mock it:
var myDate = Substitute.For<IMyDate>();
myDate.GetDate().Returns(testDate); // Error thrown here
Run Code Online (Sandbox Code Playgroud)
Please can anyone explain what I'm doing wrong?
var myDate = Substitute.For<IMyDate>();
myDate.GetDate().Returns(new DateTime(2018, 04, 05)); // Error thrown here
Run Code Online (Sandbox Code Playgroud)
Gives the same result.
这可能是由于早期测试的问题造成的。请参阅此答案,了解追踪此问题的一些步骤。我在下面包含了该答案的快照:
这很可能是由于之前针对非虚拟方法或 Returns 语句使用参数匹配器进行的测试。
不幸的是,这可能很难调试。第一步是查看当您在此装置中运行所有测试时是否出现问题。如果是这样,请检查该固定装置中 Arg.Is|Any 的所有使用,从失败的测试之前立即运行的那个开始(如果您的测试框架使用可预测的测试顺序,否则您需要查看测试日志以看看失败的测试进行了哪些测试)。
如果该固定装置没有发生这种情况,您将需要查看预先运行的固定装置,以查看剩余的 arg 匹配器来自何处。它很可能接近失败的测试。
希望这可以帮助。好消息是,下一个 NSubstitute 版本 (v4) 将在这些情况下提供更多帮助。
另请参阅:如何不使用参数匹配器。
在我们的例子中,随机测试发送此错误消息,但仅在运行所有测试时才发送。我们在从 4.6.1 迁移到 netcore 3.1 时发现了此错误。
问题在于,一个没有任何替代品的测试类正在使用该Arg.Any<int>()表达式,原因未知。
删除这段未受关注的代码Arg.Any<int>()就是解决方案。
Most likely testDate is an argument matcher (Arg.Is or Arg.Any)
The exception message is telling you just to use argument matchers as member call arguments, not as return values, but you are are using it as return value...
"Do not use in a Returns() statement or anywhere else outside of a member call"
Try
var testDate = new DateTime(); //<-- try setting the desired date as needed
var myDate = Substitute.For<IMyDate>();
myDate.GetDate().Returns(testDate);
Run Code Online (Sandbox Code Playgroud)
Reference NSubstitute: Argument matchers
| 归档时间: |
|
| 查看次数: |
14233 次 |
| 最近记录: |