Moq设置导致null

时间:2016-10-21 04:57:01

标签: c# unit-testing nunit moq

我是Unit Testing和Moq的新手,所以如果我的方法或理解完全出错,请帮助我。

我有一个我正在测试的逻辑方法。我已经对逻辑进行了评论,但它所做的就是检查'模型中的一些值。如果出现问题则返回。在我们查看的情况下,没有问题。

        public ReplyDto SaveSettings(SnowballDto model)
        {

            // Some logic here that reads from the model.

            var result = _data.SaveSettings(model);
            return result;
        }

我的测试,使用NUnit和MOQ,看起来像这样:

_logic = new SnowballLogic(mockSnowballData.Object, mockLog.Object);

           mockSnowballData
                .Setup(x => x.SaveSettings(SnowballDto_Good))
                .Returns(new ReplyDto {
                    IsSuccess = true,
                    Message = "Saved",
                    ReplyKeyID = 1
                });

在每次测试中,我都会调用私人设置功能来设置我将要使用的内容。

 private void SetupData()
        {
            SnowballDto_Good = new SnowballDto {
                FirstPaymentDate = DateTime.UtcNow,
                ID = 1,
                OrderedIDPriority = new List<int>(),
                SnowballTypeID = 1,
                TargetPayment = 1000
            };

            DebtDtoList_ThreeDebt.Clear();
            DebtDtoList_ThreeDebt.Add(new DebtDto { ID = 1, Description = "Debt 1", ManualSnowballPriority = 1, MinimumMonthlyPaymentAmount = 140, OpeningBalance = 5000, RunningData = new DebtRunningDto { Balance = 5000 }, OpeningDate = DateTime.UtcNow, SnowballID = 1, StandardRate = 10 });
            DebtDtoList_ThreeDebt.Add(new DebtDto { ID = 2, Description = "Debt 2", ManualSnowballPriority = 2, MinimumMonthlyPaymentAmount = 90, OpeningBalance = 1600, RunningData = new DebtRunningDto { Balance = 1600 }, OpeningDate = DateTime.UtcNow, SnowballID = 1, StandardRate = 15 });
            DebtDtoList_ThreeDebt.Add(new DebtDto { ID = 3, Description = "Debt 3", ManualSnowballPriority = 3, MinimumMonthlyPaymentAmount = 300, OpeningBalance = 9000, RunningData = new DebtRunningDto { Balance = 9000 }, OpeningDate = DateTime.UtcNow, SnowballID = 1, StandardRate = 20 });


        }

所以,我对MOQ的理解是我说的#34;当SnowballData课程&#34; SaveSettings&#34;叫做methid,然后是'SnowballDto_Good&#34;传入了对象,总是返回一个带有IsSuccess = true的新ReplyDto。

因此,当我拨打电话时:

var result = _data.SaveSettings(model);

它应该返回带有IsSuccess = true的ReplyDto

但是,当我在调用&#39; SaveSettings&#39;时放入断点时,它会一直返回null。

如果我将设置更改为:

.Setup(x => x.SaveSettings(It.IsAny<SnowballDto>()))

测试通过。当我给它一个真正的SnowballDto时,为什么它会返回null?

1 个答案:

答案 0 :(得分:0)

好吧,似乎你在&#34; act&#34;中传递了SnowballDto名为model的实例。部分考试

var result = _data.SaveSettings(model);

但是,在设置moq时,只有在将实例ReplyDto指定为SnowballDto_Good时才将其配置为返回新的SaveSettings。在所有其他情况下,未配置方法的模拟,并且 - 如果模拟策略松散(默认) - 它将返回SaveSettings返回类型的默认值。在这种情况下:null。

当您使用It.IsAny<SnowballDto>时,您基本上告诉moq配置SaveSettings以返回新实例,然后不仅将实例SnowballDto_Good传递给它,而是任何实例那种类型。

您需要做的是改变您的行为&#34;测试的一部分如下:

var result = _data.SaveSettings(SnowballDto_Good);

然后它将与您的原始模拟设置一起使用,因为正确的实例将传递给SaveSettings

这正是我喜欢使用MockBehavior.Strict实例化我的模拟的原因。

不会返回null,而是会抛出异常,告诉您没有正确配置模拟。

希望这有帮助。

相关问题