Now we can implement the test for the
fail call with the following code in the
// call the add method
Integer result = calc.add(3, 4);
// test that the add method returned the correct result
Fix the imports (< Fix Imports">>) to import the
Run the test (right click the file in either the source editor, or project pane, and select <>. This time the
testAdd 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
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.
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.