I’m still coming to terms with unit testing certain things and I have a question about my JUnit test for a relatively simple class:
public class Kite {
private List<String> strings = new ArrayList<String>();
public void addString(String string) { //... }
public void removeString(String string) { //... }
public List<String> getStrings() { //... }
public int getNumStrings() { //... }
}
In this case I would like to test all four methods. However the tests, now that I’ve written them, are all very similar. They (excluding the remove) all follow the basic structure of add a String to a Kite and then checking the number of Strings in the Kite object.
Is there a better way to test these “CRUD” types of methods?
Do I need to test them?
It’s better to be more specific in your testing. For addString(), you want to test that:
The string you added is present in the collection.
No other strings were added to the collection as a side effect.
If you pass null to addString(), an IllegalArgumentException (or whatever the behavior should be) is thrown
If you pass the same string in twice, the behavior is what you want (could be an IllegalArgumentException, could be a no-op)
get the idea? You want to add tests for edge cases, as well as the normal behavior (sometimes called the “happy path”). Think about your tests in terms of possible inputs, possible outputs, and code paths that can be taken.