Video in progress

Junior 🧪 Testing

In what order do you pass the expected and actual values to assertEquals, and what does it affect?

In JUnit the first argument is the expected value and the second is the actual one. If you swap them the test still works correctly, but the failure message comes out confusing.

📖 Answer

assertEquals(5, cart.size());          // correct: expected, actual
assertEquals(cart.size(), 5);          // works, but the message is backwards

When the second version fails, the log says expected: <3> but was: <5>, when in fact you expected 5 and got 3. Someone looking at the CI at night will read this wrong.

You can pass a message as the third argument:

assertEquals(5, cart.size(), "savatga 5 ta mahsulot qo'shilgan edi");
// if building the message is expensive, use a lambda: it's built only on failure
assertEquals(5, cart.size(), () -> "savat: " + cart.dump());

If you use AssertJ, this problem goes away, because its readable style forces the order: assertThat(cart.size()).isEqualTo(5). Many teams prefer AssertJ for this reason.