Junit:expect / assertThrows 不起作用

Junit: expect / assertThrows doesn't work

我的代码如何,抛出了异常: (可以说是 UserService.generate() )

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

我是如何尝试在测试中捕获这个异常的:

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

结果:

//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

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,这是一个非常强大的模拟框架。

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");
}