By kswaughs | Tuesday, July 19, 2016

How to assert exception and error message

Normally while writing junits to validators and other methods that throws exceptions, we will use either

1. @Test(expected) annotation on test method to validate only Exception class Or

2. Use try catch in test method and in catch block, write assert statement on getMessage() of exception to validate error message.

In real time, we will have to assert on both Exception type and its error message. If we use try catch for each and every business condition, out test code looks untidy and makes unreadable.

Junit library provides a special component called ExpectedException to validate both exception type and its message with the help of @Rule annotation. Let us see the below example

Exception Class
package com.kswaughs;

public class UserException extends Exception {
    
    public UserException(String message) {
        super(message);
    }

}

Validator Class
package com.kswaughs;

public class UserValidator {
    
    public void validateUserID(String userID) throws UserException {
        
        if(userID == null) {
            throw new UserException("UserId is Null");
        }
        
        if(! userID.startsWith("USER")) {
            throw new UserException("UserId is Invalid");
        }
    }

}

Validator Test
package com.kswaughs;

import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;

public class UserValidatorTest {
    
    @Rule
    public ExpectedException expectedEx = ExpectedException.none();
    
    @Test
    public void whenUserIDIsNull() throws Exception {
        
        expectedEx.expect(UserException.class);
        expectedEx.expectMessage("UserId is Null");
        
        UserValidator validator = new UserValidator();
        validator.validateUserID(null);
        
    }
    
    @Test
    public void whenUserIDIsInvalid() throws Exception {
        
        expectedEx.expect(UserException.class);
        expectedEx.expectMessage("UserId is Invalid");
        
        UserValidator validator = new UserValidator();
        validator.validateUserID("12345");
        
    }
}

Recommend this on


No comments:

Post a Comment