Question

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.

Était-ce utile?

La solution

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.

Autres conseils

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.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top