简体   繁体   中英

Getting list of objects in an OkResult

I'm trying to unit test my web services using Moq, and I have the following test:

[TestMethod()]
public void GetCoursesTest()
{
    var response = _coursesController.GetCourses();
    var contentResult = response as OkNegotiatedContentResult<List<Course>>;
    Assert.AreEqual(contentResult.Content.Count(), _educationCoursesData.Count);
}

Here, GetCourses() is:

public IHttpActionResult GetCourses() 
{
    try
    {
        return Ok(_entities.Courses.ToList().Select(course => new CourseDTO
        {
            Id = course.Id,
            CrsName = course.CrsName,
            CrsHour = course.CrsHour,
            CrsDay = course.CrsDay,
            CrsMin = course.CrsMin,
            Teacher = course.Teacher
        }));
    }
    catch
    {
        return InternalServerError();
    }
}

So its result is a list of obejcts. However, when I try to grab the list of these objects into contentResult via response as OkNegotiatedContentResult<List<Course>>; , contentResult is just a null . How can I read the list of objects from the OkResult into a variable that I can do Count() on?

If contentResult is null after

var contentResult = response as OkNegotiatedContentResult<List<Course>>;

the cast failed. The reason is you are using .ToList() to early. By using .Select(...) you are creating an IEnumerable and no List . Try this one:

return Ok(_entities.Courses.Select(course => new CourseDTO
            {
                Id = course.Id,
                CrsName = course.CrsName,
                CrsHour = course.CrsHour,
                CrsDay = course.CrsDay,
                CrsMin = course.CrsMin,
                Teacher = course.Teacher
            })ToList());

Alternatively change the cast to

OkNegotiatedContentResult<IEnumerable<Course>>;

The method under test is not returning OkNegotiatedContentResult<List<Course>> as the content was not enumerated. Either change the expected return type ( OkNegotiatedContentResult<IEnumerable<Course>> ) or update the action to enumerate the collect ( .ToList() ) before returning its data.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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