jeudi 28 avril 2016

Testing uniqueness of unique immutable objects in JUnit

I have a LicenseNumber class which is immutable and is guaranteed unique, in that if a second license number is created with the same Name and year of issue, an arbitrary serial on the end of the number will increment by 1 each time. I'm trying to test the class using JUnit as follows:

public class LicenseNumberTest {

    Name name;
    int year;
    LicenseNumber number;
    LicenseNumber dupe;

    @Before
    public void setUp() {
        name = new Name("Joe", "Bloggs");
        year = 1994;
        number = LicenseNumber.getInstance(name, year);
        dupe = LicenseNumber.getInstance(name, year);
    }

    @Test
    public void getInitialsTest() {
        assertEquals("Initials should be JB", "JB", number.getInitials());
    }

    @Test
    public void getYearTest() {
        assertEquals("Year should be 1994", 1994, number.getYear());
    }

    @Test
    public void getSerialTest() {
        assertEquals("Serial should be 0", 0, number.getSerial());
    }

    @Test
    public void uniquenessTest() {
        assertEquals("Serial should now be 1", 1, dupe.getSerial());
    }

}

Now the problem is the getSerial and uniqueness test methods are not returning what I would expect. Sometimes they pass, but often they fail because the serial is one or two numbers higher than it should be. If I create another class with a main method and do these tests 'manually' so to speak, and print output to the console, everything works just fine. But we are supposed to be using JUnit to test our classes.

Now I'm not experienced with JUnit so I'm assuming I'm doing something wrong or missing something here? I've tried initialising a new LicenseNumber object directly inside each test method, tried adding an @After method to reset all objects to null, but nothing works. I can't seem to find any other questions relating to this either.

Aucun commentaire:

Enregistrer un commentaire