Search code examples
javaunit-testingtestingjunitjunit4

Junit: expect / assertThrows doesn't work


How look my code, where exception was thrown: (Lets say it is UserService.generate() )

try {
  UrlDecoder.decode(someString); // invalid somestring here
  ...
} catch (UnsupportedEncodingException | RuntimeException e) {
  customLogger("Exception message here");
}

How i am trying to catch this exception in test:

@Test(expected = IllegalArgumentExeception.class)
public void test() {
 UserService u = new UserService();
 u.generate("invalidString");
}

RESULT:

//info logs here
java.lang.IllegalArgumentException: URLDecoder: Illegal hex characters in escape (%) pattern - For input string: "^I"
//Exception details here
java.lang.AssertionError: Expected exception: java.lang.IllegalArgumentException

Solution

  • The javadoc for URLDecoder.decode(someString) states that it will not throw an exception. I believe you meant to use URLDecoder.decode(someString, StandardCharsets.UTF_8.name()). But the Unsupported encoding exception is only thrown if the Charset you ask for is not supported. Here's one way you can make the exception get thrown, along with a way to check that it was thrown. This answer uses Mockito, which is a very powerful mocking framework.

    import org.mockito.Mockito;
    
    public class UserService {
        public void generate(String someString, String encoding) {
            try {
                URLDecoder.decode(someString, encoding);
            } catch (UnsupportedEncodingException e) {
                customLogger("Exception message here");
            }
        }
    
        public void customLogger(String string) {
            // Do something
        }
    }
    
    @Test
    public void testThrowsOnBadEncoding() {
         UserService u = Mockito.spy(new UserService());
         u.generate("vl%23%46", "unknown");
         Mockito.verify(u).customLogger("Exception message here");
    }