Given the following pseudocode:

List dohList = new List();
Foo foo   = A.getFoo();
if ( foo != null ) {
    Bar bar   = foo.getBar();
    if ( bar != null ) {
        FooBar fb = bar.getFooBar();
            if(fb != null) {
                dohList = fb.fillList();

return dohList;

The whole point of the algorithm is to fill the list with elements or else return an empty list.

Should I write unit tests for the "intermediary" null checks or should I just mock the objects inside the unit tests concerning this specific method and all is good?

  • 1
    If you're working in a language that has first-class functions, you can define a function that stitches together functions with this logic included for you. – Jack Oct 14 '14 at 23:31

Yes, you should unit test all of the branches of your function, especially one like this where it is easy to do so.

(though I might also recommend refactoring this code, as it violates the spirit, if not the letter of the Law of Demeter)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.