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

前端 未结 7 1933
余生分开走
余生分开走 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:41

    The answer from Kent Beck, creator of SUnit and JUnit (where possibly this convention originates), is:

    Line a bunch of assertEquals in a row. Having expected first makes them read better.

    However, this is so opposite to my own experience that I have to wonder if I'm misunderstanding it. Here's what I often see in tests:

    assertEquals(12345, user.getId());
    assertEquals("kent", user.getUsername());
    assertEquals("Kent Beck", user.getName());
    

    I would think this would read better with the actual value first. That puts more of the repetitive boilerplate together, aligning the method calls whose values we're testing:

    assertEquals(user.getId(), 12345);
    assertEquals(user.getUsername(), "kent");
    assertEquals(user.getName(), "Kent Beck");
    

    (And there are other reasons that I prefer this order, but for the purpose of this question about why it's the other way, Kent's reasoning appears to be the answer, even if I haven't understood it.)

提交回复
热议问题