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

前端 未结 7 1866
余生分开走
余生分开走 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条回答
  •  没有蜡笔的小新
    2021-01-31 01:31

    An ulterior purpose of assertEqual() is to demo code for human readers. Because the simplest function call is result = function(parameters), one gets used to thinking of the return value on the left and the call on the right.

    So a test that documents a function would show a literal on the left and a call on the right.

    assertEqual(15, sum((1,2,3,4,5)))
    

    That is, (expected, actual). Similarly with an expression.

    assertEqual(4, 2 + 2)
    

    If you like lining things up (PEP8 notwithstanding), the expected parameter helps being shorter on the left:

    assertEqual(42, 2 * 3 * 7)
    assertEqual(42, (1 << 1) + (1 << 3) + (1 << 5))
    assertEqual(42, int('110', int('110', 2)))
    

    Thanks Andrew Weimholt and Ganesh Parameswaran for these formulae.

提交回复
热议问题