Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why assertEquals(a, b) instead of assert(a == b)?

Tags:

unit-testing

Why most (all?) unit test frameworks have large APIs with separate functions for specifying different types of boolean conditions (eg. assertEquals, assertNotEqual, etc) instead of using single assert function (or language construct) with desired boolean expression?

like image 414
Aivar Avatar asked Oct 15 '25 16:10

Aivar


1 Answers

A simple assert will only throw AssertionError stating that the asserted conditation evaluated to false:

assert "foo".equals("boo")

java.lang.AssertionError: assertion failed

(not to mention assert string1 == string2 is incorrect due to reference comparison)

By passing both a and b the library can include them in the error message. Here: FEST assertions:

assertThat("foo").isEqualTo("boo");

//throws:
Exception in thread "main" org.junit.ComparisonFailure:
expected:<'[b]oo'> but was:<'[f]oo'>

Note that some languages are more powerful:

In Groovy (example from: Groovy 1.7 Power Assert):

a = 10
b = 9

assert 91 == a * b

yields:

Assertion failed: 

assert 91 == a * b
          |  | | |
          |  10| 9
          |    90
          false

    at ConsoleScript2.run(ConsoleScript2:4)

In Scala (ScalaTest) there is a special === operator:

assert(1 === 2)

yields 1 did not equal 2.

like image 120
Tomasz Nurkiewicz Avatar answered Oct 18 '25 23:10

Tomasz Nurkiewicz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!