Why are assertEquals() parameters in the order (expected, actual)?

前端 未结 7 1806
余生分开走
余生分开走 2021-01-31 01:28

Why do so many assertEquals() or similar function take the expected value as first parameter and the actual one as second ?
This seems counter-intuitive to me,

7条回答
  •  闹比i
    闹比i (楼主)
    2021-01-31 01:45

    This is a very intesting topic, and lots of very educational answers here too! Here is what I learn from them:

    1. Intuitive/counter-intuitive can be considered as subjective, so no matter which order it was originally defined, perhaps 50% of us would not be happy.

    2. Personally I would have preferred it were designed as assertEqual(actual, expected), because, given the conceptual similarity between assert and if, I would wish it follows the norm of if actual == expect, for example, if a == 1.

      (PS: It is true that there are different opinions which prompts to write if statement in the "reverse order", i.e. if(1==a) {...}, in order to guard you from accidentally missing one =. But that style was far from the norm, even in the C/C++ world. And if you happen to be writing Python code, you are not vulnerable to that nasty typo in the first place, because if a = 1 is not valid in Python.)

    3. The practical convincing reason to do assertEqual(expect, actual), is that the unittest library in your language likely already follows that order to generate readable error message. For example, in Python, when you do assertEqual(expected_dictionary, actual_dictionary), unittest will display missing keys in actual with prefix -, and extra keys with prefix +, just like when you do a git diff old_branch new_branch.

      Intuitive or not, this is the single most convincing reason to stick with the assertEqual(expected, actual) order. If you happen to not like it, you better still accept it, because "practicality beats purity".

    4. Lastly, if you need a way to help you remember the order, this answer compares assertEqual(expected_result, actual_calculation) to the assignment statement order result = calculate(...). It can be a good way to MEMORIZE the de-facto behavior, but IMHO it is not the undebatable reasoning of that order is more intuitive.

    So here you go. Happy assertEqual(expect, actual) !

提交回复
热议问题