使用 Moq 和 Mock 对象 - 我的列表计数在不应该是 0 时总是 0 [英] Using Moq and Mock objects - my list count is always 0 when it should not be

查看:50
本文介绍了使用 Moq 和 Mock 对象 - 我的列表计数在不应该是 0 时总是 0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不确定为什么我的 get list 方法会在我的测试中带回 0 条记录,但是当我运行我的应用程序时,它会拉回 5 个项目的列表.

I am not sure why my get list method is bringing back 0 records in my test but when I run my application it pulls back a list of 5 items.

[TestMethod]
public void TestHasListOfSurveys()
{
    var mockRepository = new Mock<ISurveyListRepository>();
    var mockModel = new List<SurveyList>();
    string testDate = DateTime.Today.AddYears(-1).ToShortDateString();

    mockRepository.Setup(x => x.GetSurveyList(testDate)).Returns(mockModel);

    var testClass = new SurveyListModel(mockRepository.Object);
    var testModel = testClass.GetSurveyList(testDate);

    mockRepository.VerifyAll();

    Assert.IsTrue(testModel.Count > 0);
}

我做错了什么?

更新

好吧,我想我知道我现在做了什么.因此,如果我将其更改为:

Okay I think I see what I did now. So if I change it to:

    var mockModel = new List<SurveyList>();
    mockModel.Add(new SurveyList { SurveyID = 1, SurveyName = "test1" });
    mockModel.Add(new SurveyList { SurveyID = 2, SurveyName = "test2" });
    mockModel.Add(new SurveyList { SurveyID = 3, SurveyName = "test3" });

然后它会有一个计数并且很好,然后我的模拟对象有项目.

then it will have a count and be fine and then my mock object has items.

推荐答案

ISurveyListRepository 依赖项在您的测试中被模拟替换,您的应用程序可能使用其他实现.

ISurveyListRepository dependency is replaced by a mock in your test, your application probably uses an other implementation.

var mockModel = new List<SurveyList>();
mockRepository.Setup(x => x.GetSurveyList(testDate)).Returns(mockModel);

这些行使模拟返回一个空列表,这可能就是您的测试失败的原因.如果您向列表中添加一些项目,您的测试将通过.另一方面,应用程序使用一个实现 ISurveyListRepository 的类.找到那个类,你就会明白为什么它会返回 5 个项目.

These lines make the mock return an empty list, that's probably why your test is failing.If you add some items to the list, your test will pass. On the other hand, the application uses a class implementing ISurveyListRepository. Find that class and you will see why it's returning 5 items.

这篇关于使用 Moq 和 Mock 对象 - 我的列表计数在不应该是 0 时总是 0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆