Wednesday, August 1, 2012

JUnit: test if a method throws correct exception

How do you write a JUnit test to check if it throws the correct exception:

You can add the following to the annotated test:
@Test(expected=RequestValidationException.class)

1:  @Test(expected=RequestValidationException.class)  
2:          public void testValidateHeader_contentTypeInvalidValue() throws Exception  
3:          {      
4:              EasyMock.expect(servletRequest.getHeader("content-type")).  
5:                 andReturn("application/xml;charset=utf8");      
6:              EasyMock.replay(servletRequest, encryptionHelper);  
7:              Whitebox.invokeMethod(validator, "validateHeaders", servletRequest);  
8:          }  

Got to know it from here:
http://www.junit.org/node/390

Additional JUnit tip: WhiteBox comes from org.powermock.reflect.Whitebox and is used for invoking private methods

No comments:

Post a Comment