单元测试对集合排序的方法 [英] Unit test a method that sorts a collection

查看:85
本文介绍了单元测试对集合排序的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一种方法可以根据如下属性对集合进行排序:

I have a method that sorts a collection based on a property like this:

public List<Student> GetAllStudents()
{
    return _studentCatalogContext.Student.Where(x => (x.Course != 2 && x.Course != 6))
                                 .OrderByDescending(x => x.EnrollDateTime).ToList();
}

因此,在这种情况下,我们的想法是让最近注册的Student在前.

So the idea is to have, in this case, the most recently enrolled Student first.

由于方法调用的结果将是具有最新注册的排序列表,因此我编写了如下测试:

Since the result of the method call will be a sorted list with the newest enrollment first I wrote a test like this:

[TestMethod]
public void Calling_GetAllStudents_ReturnsSortedListOfStudents()
{
    var studentsList = new List<Student> {
    new Student {
                     Id = "123",
                     EnrollTime = "02/22/16 14:06:56 PM",
                     Course = 1
                 },
     new Student {
                     Id = "456",
                     EnrollTime = "03/30/16 12:50:38 PM",
                     Course = 3
                 }
                 };

    _studnentRepository.Setup(x=>x.GetAllStudents()).Returns(studentsList);

    Assert.AreEqual("02/22/16 14:06:56 PM", studentsList[0].EnrollTime);
}

建议此测试无效,因为它会先设置一个值然后对其进行断言.

It's been suggested that this test does is not valid in that it sets a value and then asserts on it.

在这种情况下,我该如何编写正确的单元测试?

How would I write a correct unit test in this case?

推荐答案

测试列表是否正确排序基本上是无关紧要的,因为它是一种内置的框架方法,您已经假设它已经过测试并证明是正确的.框架设计人员(在这种情况下为Microsoft).

Testing that a list is sorted correctly is largely irrelevant because it is an in-built framework method that (you would assume) has been tested and proven correct by the framework designers (Microsoft in this case).

对此方法的更好测试是确保仅返回不在课程2或6中的学生,因为这是您在Where方法中的自定义逻辑.

A better test for this method would be to ensure that only students who are not in Course 2 or 6 are returned, since that is your custom logic inside the Where method.

因此,您的测试可能类似于:

So, your test could be something like:

[TestMethod]
public void Calling_GetAllStudents_ReturnsSortedListOfStudents()
{
    var studentsList = new List<Student> {
    new Student {
                     Id = "123",
                     EnrollTime = "02/22/16 14:06:56 PM",
                     Course = 1
                 },
     new Student {
                     Id = "456",
                     EnrollTime = "03/30/16 12:50:38 PM",
                     Course = 2
                 }
                 };

    // mock out student repository to return list    

    var studentsList = _studentRepository.GetAllStudents();

    Assert.AreEqual(1, studentsList.Count);
    Assert.AreEqual("123", studentsList[0].Id);
}

这篇关于单元测试对集合排序的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆