单元测试对集合进行排序的方法

时间:2016-04-26 04:12:43

标签: c# unit-testing mocking moq

我有一个方法可以根据这样的属性对集合进行排序:

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

因此,在这种情况下,首先要注册的是最近注册的学生。

由于方法调用的结果将是一个带有最新注册的排序列表,我首先写了一个这样的测试:

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

有人建议此测试无效,因为它设置了一个值,然后对其进行断言。

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

2 个答案:

答案 0 :(得分:1)

你测试它是一个空测试(它测试你构建的列表有你刚刚放在那里的第一个元素)。

在其当前表单中,您的accepted answer存在同样的问题。它设置了一个模拟你的存储库,然后验证模拟返回你告诉模拟的信息。

要有效地测试存储库逻辑,您需要模拟其依赖项,在本例中为_studentCatalogContext。由于您未在问题中提供此信息,因此我将假设以下课程:

public class Student {
    public string Id {get;set;}           // Weird this is a string not int
    public string  EnrollTime {get;set;}  // Weird this is a string not date
    public int Course  {get;set;}
}

public class StudentCatalogContext : DbContext
{
    public virtual IDbSet<Student> Student { get; set; }
}

public class StudentRepository
{
    private StudentCatalogContext _studentCatalogContext;
    public StudentRepository(StudentCatalogContext context)
    {
        _studentCatalogContext = context;
    }
    public List<Student> GetAllStudents()
    {
        return _studentCatalogContext.Student.Where(x => (x.Course != 2 && x.Course != 6))
                                     .OrderByDescending(x => x.EnrollTime).ToList();
    }
}

注意,我正在将目录上下文注入存储库。这是必需的,因此可以嘲笑它。另请注意,我已将您的LINQ查询中的EnrolledDateTime重命名为EnrollTime,以便与其余代码示例匹配。

然后可以按如下方式测试此代码:

// Construct the data to be returned by the student set mock.
// Note, you don't want this to be in the order that you're expecting
// otherwise, how do you know if it's been sorted...
var studentData = 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
                 }
}.AsQueryable();

// Setup a mock of the student set, which returns the canned data
// prepared above
var dbSetMock = new Mock<IDbSet<Student>>();
dbSetMock.Setup(m => m.Provider).Returns(studentData.Provider);
dbSetMock.Setup(m => m.Expression).Returns(studentData.Expression);
dbSetMock.Setup(m => m.ElementType).Returns(studentData.ElementType);
dbSetMock.Setup(m => m.GetEnumerator()).Returns(studentData.GetEnumerator());

// Create a mock of the catalog context that returns
// the mocked set prepared above
var contextMock = new Mock<StudentCatalogContext>();
contextMock.Setup(x=>x.Student).Returns(dbSetMock.Object);

// Create the system under test, injecting the mock context
var repo = new StudentRepository(contextMock.Object);

// Call the method that we're actually testing
var fetchedData = repo.GetAllStudents();

// Validate that the information returned is what we're expecting
Assert.AreEqual("02/22/16 14:06:56 PM", fetchedData[0].EnrollTime);

值得指出的是,上述测试失败了。这是因为测试中的代码对EnrollTime进行了降序排序,因此列表中的第一项是EnrollTime为&#34; 03/30/16 12:50:38 PM&#34;

答案 1 :(得分:-1)

测试列表是否正确排序在很大程度上是无关紧要的,因为它是一个内置的框架方法(您可以认为)已被框架设计者(在本例中为Microsoft)测试并证明是正确的。

更好的测试方法是确保只返回课程2或6中的学生,因为这是Where方法中的自定义逻辑。

所以,你的测试可能是这样的:

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