how do you test if statements with junit?

2019-07-17 15:00发布

问题:

I can't seem to find any tutorials online that address this

I have this if statement:

if (basket.getCustomerId() != null) {
                Basket exBasket = findBasketByCustomerId(basket.getCustomerId());
                if (exBasket != null && exBasket.getBasketId() != null) {
                    return exBasket;
                }

and I want to write a unit test that will test each individual line to see if it is doing the right thing.

Any ideas?

@Test
    public void testBasketWithANullCustomerId(){
        basketInformationServiceImpl.createBasket(mockBasket);
        assertNotNull(mockBasket.getCustomerId());
    }

回答1:

The purpose of unit testing isn't to test statements but methods. The right thing to do is not to consider this line, but to consider the method that it appears in, and ask what you want that method to do: what sort of input does it take, and what sort of output should it produce?

Then write tests that take some typical inputs, and check that they give correct outputs, and also some edge case inputs (like null, 0, Integer.MAX_VALUE, etc.) and check that you get the right outputs for those too.

If this is your entire method (which actually it can't be, but if it's the essence of it), I'd test:

  • a basket with a null customer ID;
  • a null basket (unless you're certain this can never happen), because currently this code will give a NullPointerException;
  • a basket that has a customer ID that should allow you to find a known exBasket;
  • a basket that has a customer ID that will return an exBasket of null;
  • a basket that has a customer ID that will return an exBasket that isn't null, but whose basket ID is null.


回答2:

Assuming this is an excerpt from a method you're trying to test, it sounds like you need at least two test cases - one where basket.getCustomerId() is expected to be null and one where it isn't. In both cases you should be able to test the method's return value (I'm assuming a Basket will be returned as well in the event getCustomerId() is null) against the expected outcome.



回答3:

To test in the way you seem to want to (emphasizing line coverage), you need a test for each situation you want to test (for example, one test for a null basketId, another for a not null basketId, another for another case you wish to test).

Mocking frameworks (such as Mockito) can be used to to set preconditions for a test. For an example of one case you can say

@Test
public void myTestWithNonNullBasketId() {
    Basket inputBasket = Mockito.mock(Basket.class);
    when(inputBasket.getBasketId()).thenReturn(1); //Or whatever we want basketId to return, null if you want to check that case.
    ... //More mocking as needed, presumably to dictate whatever findBasketByCustomerId might return.

    //Call the method you are testing, use org.junit.Assert assertions to check outputs.
}


标签: java junit