jeudi 4 avril 2019

Unit Test Equals Method that covers both the branches in Java

I have been trying to get my head around unit testing equals method in java to cover all branches. There is one branch missing. I tried to look up couple of resources, but was not very helpful. Here is my code which I am trying to unit test it.

public boolean isValid(Item item) {

    return !StringUtils.isEmpty(item.getCat()) &&        //both branches covered
            !StringUtils.isEmpty(item.getDog()) &&   //both branches covered
            !StringUtils.isEmpty(item.getDogCat()) &&       //both branches covered
            String.format("%s|%s", item.getDog(), item.getCat())  //here one branch missing
                    .equals(item.getDogCat());
}


Unit Test:

    boolean expectedValue = false;

    @Test
    public void testIsValidWhenCatIsNull() {
        boolean actualValue = itemValidator.isValid(ITEM_1);
        Assert.assertEquals(expectedValue, actualValue);
    }

    @Test
    public void testIsValidWhenDogIsNull() {
        boolean actualValue = itemValidator.isValid(ITEM_2);
        Assert.assertEquals(expectedValue, actualValue);
    }

    @Test
    public void testIsValidWhenDogCatIsNull() {
        boolean actualValue = itemValidator.isValid(ITEM_3);
        Assert.assertEquals(expectedValue, actualValue);
    }

    @Test
    public void testIfDogCatMatchesConcatenatedDogCat() {
        itemValidator.isValid(ITEM_7);
        Assert.assertEquals(String.format("%s|%s", "bow", "meow"), ("bow|meow"));
}


Unit testing world is quite new to me, any help is appreciated.

Aucun commentaire:

Enregistrer un commentaire