The importance of phased assertions in unit tests

When writing unit tests, there are times when you can create an Assert for each condition that may fail, or an Assert that catches all such conditions. C # example:

Dictionary<string, string> dict = LoadDictionary();
// Optional Asserts:
Assert.IsNotNull(dict, "LoadDictionary() returned null");
Assert.IsTrue(dict.Count > 0, "Dictionary is empty");
Assert.IsTrue(dict.ContainsKey("ExpectedKey"), "'ExpectedKey' not in dictionary");
// Condition actually interested in testing:
Assert.IsTrue(dict["ExpectedKey"] == "ExpectedValue", "'ExpectedKey' is present but value is not 'ExpectedValue'");

Is it important for a large project with several people in a similar situation to add “Optional confirmations”? There is more work (if you have a lot of unit tests), but it will be more clear where the problem is.

I use VS 2010 and integrated testing tools, but I ask the question as a general one.

+3
source share
4 answers

, - , , . , .

" ", . , , , , . ( TC) , , , - . , .

, - .

, , , "/ " aproach, , , (LoadDict(), ..), , " " , " ", LoadDictionary() , ( ). , , , . - / TC.

+2

, , , , .

  • TDD , .
  • , , .

"" , .

  • , LoadDictionary(); null,
  • , LoadDictionary();
  • .

, . , , , .

+1

, .

, , . , , / - .

, , , . , , , (, , ), .

, , Asserts, . , , Asserts , , - , .


, , ( ), , , , Asserts. , , dict null, ? , , , , , - .

, , , - . , . , , , , , . - , , , .

. , , , .

+1

, , .

, :

Assert.IsTrue(dict["ExpectedKey"] == "ExpectedValue",
              "'ExpectedKey' is present but value is not 'ExpectedValue'");

, LoadDictionary() null? unit test, C/++, . , dict null, .

: , ? , . , , (, ), : , , . .

, , , , .

Finally, using some kind of equality statement will give a more accurate error message:

Assert.Equal("ExpectedValue", dict["ExpectedKey"],
              "Incorrect value for 'ExpectedKey'");

The error should be something like "expected: ExpectedValue, actual:". Knowing the wrong value for a key can be helpful.

+1
source

Source: https://habr.com/ru/post/1747909/