Are multiple asserts bad in a unit test? Even if chaining?

后端 未结 6 1384
借酒劲吻你
借酒劲吻你 2020-12-24 01:23

Is there anything wrong with checking so many things in this unit test?:

ActualModel = ActualResult.AssertViewRendered()        // check 1
                           


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-12-24 01:51

    I know that this is an old question but I thought I'd add my bit.

    Generally I'd have as few assertions as possible in each test case. Tests can be often be written to save having lots of different assertions.

    Suppose I have unit tests for a method which creates a salutation (eg Mr Smith) from the components of a name. I want to check this with a large number of different scenarios, it is unnecessary to have a separate test for each.

    Given the following code, there are many different assertions. When they fail you can fix them one at a time until the assertions stop.

    Assert.AreEqual("Mr Smith", GetSalutation("Mr", "J", "Smith"));
    Assert.AreEqual("Mr Smith", GetSalutation("Mr", "John", "Smith"));
    Assert.AreEqual("Sir/Madam", GetSalutation("", "John", "Smith"));
    Assert.AreEqual("Sir/Madam", GetSalutation("", "J", "Smith"));
    

    An alternative to this is to keep a count of issues and assert this at the end.

    int errorCount = 0;
    string result;
    
    result = GetSalutation("Mr", "J", "Smith");
    if (result == "Mr Smith")
        errorCount++;
    
    result = GetSalutation("Mr", "John", "Smith");
    if (result == "Mr Smith")
        errorCount++;
    
    Assert.AreEqual(0, errorCount);
    

    In a real world situation I'd probably add some Trace commands to write the detail of the individual tests which failed to the output window

提交回复
热议问题