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

天大地大妈咪最大 提交于 2019-12-11 01:52:51

问题


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

What am I doing wrong?

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.


回答1:


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

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.




回答2:


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.



来源:https://stackoverflow.com/questions/23374314/using-moq-and-mock-objects-my-list-count-is-always-0-when-it-should-not-be

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!