labs / tiddlers / content / labs / lab02 / _Labs_02_Testing the Add

Now we can implement the test for the add method.

  1. 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));
  2. Fix the imports (<

    Fix Imports">>) to import the assertThat and is methods.

  3. Run the test (right click the file in either the source editor, or project pane, and select <

    >. This time the testAdd method should pass.

  4. 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 -.

  5. 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.

  6. 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.