首页 > 解决方案 > Junit:期望 / assertThrows 不起作用

问题描述

我的代码在哪里抛出异常:(假设它是 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

标签: javaunit-testingtestingjunitjunit4

解决方案


URLDecoder.decode(someString)的javadoc声明它不会抛出异常。我相信您打算使用 URLDecoder.decode(someString, StandardCharsets.UTF_8.name())。但是仅当您要求的字符集不受支持时才会抛出 Unsupported encoding 异常。这是一种可以让异常被抛出的方法,以及一种检查它是否被抛出的方法。这个答案使用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");
}

推荐阅读