【问题标题】:Nsubstitute mock method with any arguments is not working .net core带有任何参数的 Nsubstitute 模拟方法都不起作用.net核心
【发布时间】:2019-07-12 12:44:17
【问题描述】:

我正在尝试使用Arg.Any<T>() 参数模拟该方法。模拟方法在调用 .netframework 而不是 netcoreapp 时正确重定向。

这是一个与此问题类似的link,但此问题似乎是 NSubstitute 在网络核心中无法正常工作。

Github 链接是here

注意:不是传递 Arg.Any 值,而是传递特定的参数值,它可以正常工作

在 netframework(4.5.1) 和 net core app(2.1) 库中进行比较。

Dotnet Core 结果:

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

【问题讨论】:

  • 我认为您可以将此作为问题发布到 nsub github。

标签: c# .net-core nsubstitute


【解决方案1】:

行为不一致的问题是由参数匹配器的错误使用引起的。在你的测试的最后一行你做

Exception exception = Assert.Throws(
() => b.doSomeB(Arg.Any()));

所以你在 NSubstitute “上下文”之外使用 Arg.Any - 这意味着你没有指定 Returns、Throws 或任何其他应该执行的 NSubstitute 操作。请查看文档herehere。长话短说

只有在指定调用以设置返回值、检查收到的调用或配置回调时才应使用参数匹配器(例如:ReturnsReceivedWhen)。在其他情况下使用 Arg.IsArg.Any 可能会导致您的测试以意想不到的方式运行。

当您将Assert.Throws 中的Arg.Any 替换为实际值时,测试将变为绿色。

【讨论】:

    猜你喜欢
    • 2019-07-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-05-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多