简体   繁体   English

使用Moq和Mock对象-我的列表计数始终为0,而​​不应为0

[英]Using Moq and Mock objects - my list count is always 0 when it should not be

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. 我不确定为什么我的get list方法会在测试中返回0条记录,但是当我运行我的应用程序时,它会拉回5条记录。

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

What am I doing wrong? 我究竟做错了什么?

UPDATE UPDATE

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 dependency is replaced by a mock in your test, your application probably uses an other implementation. 在您的测试中, ISurveyListRepository依赖项已由模拟替代,您的应用程序可能使用其他实现。

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

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 . 另一方面,应用程序使用实现ISurveyListRepository的类。 Find that class and you will see why it's returning 5 items. 找到该类,您将看到为什么它返回5个项目。

Instead of : 代替 :

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

you should write something like : 你应该写这样的东西:

mockRepository.Setup(x => x.GetSurveyList(It.IsAny<String>)).Returns(mockModel);

otherwise, your mock will not be used . 否则,将不会使用您的模拟。

anyway, if you tell it to return mockModel which is empty, you will get obviously empty list. 无论如何,如果您告诉它返回为空的mockModel ,您显然会得到空列表。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM