Skip to main content

Junit Expected Exception checking

I was writing a temporary REST api for folder search until the elasticsearch based api is live. The api has some validation code and I was trying to test it.

    @POST
    @Consumes(MediaType.APPLICATION_JSON)
    @Produces(MediaType.APPLICATION_JSON)
    public Response search(@Context User user, FolderSearchRequest folderSearchRequest) throws ApplicationException {
        if (StringUtils.length(folderSearchRequest.getQuery()) < 3) {
            throw new GenericRestServiceException(ErrorCode.FailedValidation, INVALID_QUERY_MSG);
        }
        if (folderSearchRequest.getStart() < 0) {
            throw new GenericRestServiceException(ErrorCode.FailedValidation,
                    INVALID_START_MESSAGE);
        }
        if (folderSearchRequest.getLimit() <= 0) {
            throw new GenericRestServiceException(ErrorCode.FailedValidation,
                    INVALID_LIMIT_MESSAGE);
        }

At first I was writing code like

    @Test(expected=GenericRestServiceException.class)
    public void testQueryMinimumChars() throws ApplicationException {
        sut.search(null, new FolderSearchRequest("te", 0, 20));
    }
    @Test(expected=GenericRestServiceException.class)
    public void testNegativeStart() throws ApplicationException {
        sut.search(null, new FolderSearchRequest("test", -1, 20));
    }

Only issue with this was that I wont know what exception is thrown. It seems Junit has a concept of ExpectedExceptions and you can check much more about expected exceptions than the annotation way.

The same code can be written as

public class FolderSearchEndPointUnitTest {
    private FolderSearchEndPoint sut = new FolderSearchEndPoint();
    @Rule
    public ExpectedException expectedException = ExpectedException.none();

    @Test
    public void testQueryMinimumChars() throws ApplicationException {
        expectedException.expect(GenericRestServiceException.class);
        expectedException.expectMessage(FolderSearchEndPoint.INVALID_QUERY_MSG);
        sut.search(null, new FolderSearchRequest("te", 0, 20));
    }

    @Test
    public void testNegativeStart() throws ApplicationException {
        expectedException.expect(GenericRestServiceException.class);
        expectedException.expectMessage(FolderSearchEndPoint.INVALID_START_MESSAGE);
        sut.search(null, new FolderSearchRequest("test", -1, 20));
    }
}

Edit: I had to change this code to do more detail exception checking and that is mentioned at http://astartupguy.blogspot.com/2014/09/junit-expected-exception-checking-part2.html

Comments