【问题标题】:why does it always return Null result even I Arrange the method in NSubstitute?为什么即使我在 NSubstitute 中安排方法,它也总是返回 Null 结果?
【发布时间】:2021-12-31 22:42:28
【问题描述】:

我尝试安排一个工厂返回一个服务实例。

然后我安排了这个服务,但是服务中的方法总是返回null,即使我安排了方法,为什么?

这是我的示例代码,有人可以帮助我吗?提前致谢!

using Moq;
using NSubstitute;
using Xunit;

namespace ConsoleApp1
{
    public interface IFactory
    {
        IMyService CreateInService(int number);
    }
    public  interface IMyService
    {
        (Status?,Status?)GetName(string name);
    }
    
    public enum Status
    {
        UnKnown = 0,
    }
    
    public class TupleTest
    {

        [Fact]
        public void GetTupleTest()
        {
            (Status?,Status?) exceptedStatusTuple = (Status.UnKnown,Status.UnKnown);
            
            var factory = Substitute.For<IFactory>();
            var myService = Substitute.For<IMyService>();

            factory.CreateInService(It.IsAny<int>()).Returns(myService);
            myService.GetName(It.IsAny<string>()).ReturnsForAnyArgs(exceptedStatusTuple);

            var result = factory.CreateInService(100).GetName("test");
            
            //result.item1 is null, it should be Status.UnKnown!
            Assert.Equal(result.Item1,exceptedStatusTuple.Item1);
            //result.item2 is null,it should be Status.UnKnown!
            Assert.Equal(result.Item2,exceptedStatusTuple.Item2);
        }
    }
}

【问题讨论】:

    标签: c# xunit nsubstitute


    【解决方案1】:

    您似乎混淆了 Moq 和 NSubstitute 调用。尝试注释掉 using Moq; 行并使用该测试修复编译错误。

    我可以看到的一个例子是It.IsAny 是一个起订量电话。 NSubstitute 需要为 Arg.Any

    【讨论】:

    • 太棒了!这真的很有帮助!
    猜你喜欢
    • 2011-12-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多