jeudi 25 août 2016

Generic way to unit-test that all Collections can not be null

I often create objects that contain some kind of Collection (Set, List, whatever). They can never be null. If null is passed by constructor or setter, then new instance of empty collection is created. Here is an example with error (marked by comments).

package com.myapp;

import com.google.common.collect.Lists;

import java.util.List;

public class MyClass {
    private List<String> myNeverNullList1;
    private List<String> myNeverNullList2;

    public MyClass(List<String> myNeverNullList1, List<String> myNeverNullList2) {

        this.myNeverNullList1 = myNeverNullList1==null? Lists.newArrayList():myNeverNullList1;
        this.myNeverNullList2 = myNeverNullList2==null? Lists.newArrayList():myNeverNullList2;
    }

    public void setMyNeverNullList1(List<String> myNeverNullList1) {
        this.myNeverNullList1 = myNeverNullList1==null? Lists.newArrayList():myNeverNullList1;
    }

    public void setMyNeverNullList2(List<String> myNeverNullList2) {
        //OOPS, I forgot to put the null check here, should be caught by Unit Tests
        this.myNeverNullList2 = myNeverNullList2;
    }
}

I test this behavior in unit tests by unit tests, but it is tedious to write such simple test for each collection. Is there any library, that would help me to test this kind behavior automatically?

Aucun commentaire:

Enregistrer un commentaire