Now we can implement the test for the add
method.
Replace the fail
call with the following code in the testAdd
method:
// call the add method Integer result = calc.add(3, 4); // test that the add method returned the correct result assertThat(result, is(7));
Fix the imports (<
Fix Imports">>) to import theassertThat
and is
methods. Run the test (right click the file in either the source editor, or project pane, and select <
>. This time thetestAdd
method should pass. We aren't done with the testAdd
method yet --- we need to check that our test is sufficient. Break the add
method in the Calculator
class by changing the +
operator to a -
.
Run the test again. You should see that the testAdd
test now fails. This verifies that our test is capable of detecting when our method is returning an incorrect result. Fix the method again by putting the +
operator back.
This test still isn't all that comprehensive --- we have only tested one combination of numbers. Add the following to the testAdd
method:
assertThat(calc.add(1,2), is(3)); assertThat(calc.add(5,-4), is(1)); assertThat(calc.add(-5,4), is(-1)); assertThat(calc.add(4,-8), is(-4)); assertThat(calc.add(-1,-5), is(-6));
This should give the add
method a good work out and also check that it can handle negative numbers for each parameter combination. We are cutting out the intermediate variable result
here to make the code a little more compact.
The assertThat
and is
methods are part of the Hamcrest library. Hamcrest provides a 'literate' interface for evaluating the results of tests. A literate interface is when you write code that reads a lot like spoken language (English in this case) --- "assert that 1+2 is 3". JUnit only has very basic assert
methods built into it since it is expected that you will use something better like Hamcrest to evaluate the results.
If any of these assertions are not true then the test will fail.