views:

47

answers:

2

Suppose that you have the following logic in place:

processMissing(masterKey, masterValue, p.getPropertiesData().get(i).getDuplicates());

public StringBuffer processMissing(String keyA, String valueA, Set<String> dupes) {
// do some magic
}

I would like to write a jUnit test for processMissing, testing its behavior in event dupes is null.

Am i doing the right thing here? Should I check how method handles under null, or perhaps test method call to make sure null is never sent?

Generally speaking, what is the approach here? We can't test everything for everything. We also can't handle every possible case.

How should one think when deciding what tests to write?

I was thinking about it as this:

  1. I have a certain expectation with the method
  2. Test should confirm define my expectation and confirm method works under that condition

Is this the right way to think about it?

Thanks and please let me know

A: 

If you want to ensure that people don't call your API with a null argument you may want to consider using annotations to make this explicit, JSR 305 covers this, and its used in Guava. Otherwise you're relying on users reading javadoc.

As for testing, you're spot on in that you can't handle every possible case, assuming you don't want to support null values, I'd say that you may want to throw an IllegalArguemntException rather than a NullPointerException so you can be explicit about what is null, then you can just test for that exception being thrown - see JUnit docs.

Jon Freedman
+1  A: 

First, define whether null is a valid value for the parameter or not.

If it is, then yes, definitely test the behavior of the method with null.

If it is not, then:

  • Specify that constraint via parameter documentation.
  • Annotate that constraint on the parameter itself (using an annotation compatible with the tool below).
  • Use a static analysis tool to verify that null is never passed.
  • No unit test is required for the invalid value unless you're writing code to check for it.

The static analysis tool FindBugs supports annotations such as @NonNull, with some limited data-flow analysis.

I personally think it would be unnecessarily expensive within large Java codebases to always write and maintain explicit checks for NULL and corresponding, non-local unit tests.

Andy Thomas-Cramer