我试图用Arg.Any<T>()参数来模拟这个方法。模拟的方法在.netframework调用时正确地重定向,而不是在netcoreapp中重定向。
这里有一个类似于这个问题的链接,但是这个问题似乎是NSubstitute在net中不能正常工作。
而Github是这里
注释:它不是传递Arg.Any值,而是传递特定的参数值,而是运行良好的
在netframework(4.5.1)和net应用程序(2.1)库中进行了比较。
Dotnet核心结果:
Test Name: ClassLibrary1.Class1.Method
Test FullName: ClassLibrary1.Class1.Method
Test Source: C:\Users\mmohan\source\repos\ClassLibrary1\ClassLibrary1\Class1.cs : line 10
Test Outcome: Failed
Test Duration: 0:00:00.177
Result StackTrace: at ClassLibrary1.Class1.Method() in C:\Users\mmohan\source\repos\ClassLibrary1\ClassLibrary1\Class1.cs:line 16
Result Message:
Assert.Throws() Failure
Expected: typeof(System.FormatException)
Actual: (No exception was thrown)网框架结果:
Test Name: ClassLibrary1.Class1.Method
Test FullName: ClassLibrary1.Class1.Method
Test Source: C:\Users\mmohan\source\repos\SampleTestIssue\ClassLibrary1\Class1.cs : line 10
Test Outcome: Passed
Test Duration: 0:00:00.292我的代码:
using NSubstitute;
using System;
using Xunit;
namespace ClassLibrary1
{
public class Class1
{
[Fact]
public void Method()
{
IB b = Substitute.For<IB>();
A a = new A(b);
b.doSomeB(Arg.Any<string>()).Returns(x => { throw new FormatException("Something there"); });
a.doSomeA("");
Exception exception = Assert.Throws<FormatException>(
() => b.doSomeB(Arg.Any<string>()));
}
}
public class A
{
public IB _b;
public A(IB b)
{_b = b;}
public void doSomeA(string aa)
{
try
{ _b.doSomeB("");}
catch (Exception ex){ }
}
}
public class B : IB
{
public string doSomeB(string bb)
{
try{ }
catch (Exception ex){ }
return "";
}
}
public interface IB
{
string doSomeB(string bb);
}
}发布于 2019-07-13 12:21:24
不一致行为的问题是由于错误地使用了论点匹配。在测试的最后一行,您可以这样做。
Exception exception = Assert.Throws(
() => b.doSomeB(Arg.Any()));因此,您在Arg.Any“上下文”之外使用NSubstitute --意思是您没有指定应该执行的返回、抛出或任何其他NSubstitute操作。请看一下文档这里和这里。长话短说
参数匹配器只应用于指定用于设置返回值、检查接收到的调用或配置回调(例如:使用
Returns、Received或When)的调用。在其他情况下使用Arg.Is或Arg.Any会导致您的测试以意想不到的方式运行。
当用实际值替换Arg.Any中的Assert.Throws时,测试将是绿色的。
https://stackoverflow.com/questions/57007262
复制相似问题