Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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, so is there a particular reason for this unusual order ?

like image 452
jor Avatar asked Mar 08 '10 21:03

jor


People also ask

What is expected and actual in assertEquals?

assertEquals. Asserts that two object arrays are equal. If they are not, an AssertionError is thrown. If expected and actual are null , they are considered equal.

What are the parameters for the assertEquals function?

Procedure assertEquals has two parameters, the expected-value and the computed-value, so a call looks like this: assertEquals(expected-value, computed-value);

Which assertion should you use to compare an expected value to an actual value?

assertEquals() is a method that takes a minimum of 2 arguments and compares actual results with expected results. If both match, then the assertion is passed and the test case is marked as passed.

What is the correct syntax to check whether the expected and actual values are equal?

assertArrayEquals(expected, actual)


1 Answers

The answer from Kent Beck, co-creator of JUnit (where possibly this convention originates, since his earlier SUnit doesn't appear to have included assertEquals):

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

In the initial version of my answer, I said that I didn't understand this. 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.)

However, Bob Stein has a comment below (much like this one) that suggests a couple things that "expected first" has going for it. The main idea is that expected values are probably typically shorter -- often literals or variables/fields, rather than possibly complex method calls. As a result:

  • It's easier to identify both the expected and actual values at a glance.
  • It's possible to use a small amount of extra whitespace to align them (if you prefer that kind of thing, though I don't see it used in the earliest JUnit commit I could find easily):
assertEquals(12345,       user.getId()); assertEquals("kent",      user.getUsername()); assertEquals("Kent Beck", user.getName()); 

Thanks, Bob!

like image 84
Chris Povirk Avatar answered Nov 15 '22 17:11

Chris Povirk