I am trying to mock the result of a repository method which will return me a list of class objects. Am having a check if the result contains data then the API will return the status code depending on the check. Am able to mock the result but it throwing null reference exception while it checking the results contains data. Here is the code for controller and test case.
public IActionResult Get([FromQuery] FilterRequst request)
{
IEnumerable<Student> result = _repository.GetAll(Mapper.Map<StudentFilter>(request));
if (result != null && result.Count() > 0)//here throwing null reference exception
{
List<StudentModel> model = Fill(result.ToList());
var response = new StudentListModel()
{
TotalRecords = model.Count,
Items = model
};
return new ObjectResult("OK")
{
StatusCode = (int?)HttpStatusCode.OK,
Value = response
};
}
return new ObjectResult("No Content")
{
StatusCode = (int?)HttpStatusCode.NoContent,
Value = "No Content"
};
}
Testcase:
public void StudentGetAllTestReturnsStudents()
{
var fakeStudents = new Mock<IEnumerable<Student>>();
_mockRepository.Setup(x => x.GetAll(It.IsAny<Filter>())).Returns(fakeStudent.Object);
_studentController = new StudentsController(_mockRepository.Object);
Mapper.Initialize(cfg =>
{
cfg.CreateMap<FilterModel, Filter>();
});
// Act
var actionResult = _studentController.Get(It.IsAny<FilterModel>());
var result = actionResult as ObjectResult;
var model = result.Value as StudentListModel;
// Assert
Assert.IsNotNull(result);
Assert.AreEqual(StatusCodes.Status200OK, result.StatusCode);
Assert.IsNotNull(model);
}
How can I mock the IEnumerable<Student>
which can be checked for not null
and Count
?