javaunit-testingjunitstateless-session-beandefensive-programming

Error checking in business methods a.k.a doing defensive programming


I am starting to add tests to a large java code base. I often see the following in the session beans I am testing:

public OrderDTO getOrderDTO(Long id) {
    Order o = (Order)entityManager.find(Order.class, id);
    OrderDTO dto = new OrderDTO(o.getId(), o.getCurrency());
    return dto;
}

Its quit easy to write a unit test to break this code (send in a null or a non existing id). When I did that half the developers of the team said:

We are not error checking everything. If you parameter is rubbish you will know fast!

The other half said:

We must add ifs to the id and then to the o and if any of them are null the null is what we return.

Isn't the point of unit testing to find exactly thees kind of issues? (Yes, I am asking for an opinion!)

Yes, switching from Long to long will remove one if.


Solution

  • While this is somewhat opinion based, few people would say it's correct to return null if given null as a parameter. If I were to add anything, it would be at most a IllegalArgumentException (or even NPE) when null is passed in.

    A test could be created to check that the method fails in a consistent fashion, but it would really be testing the behaviour of the JPA provider and not your code.