gpt4 book ai didi

java - 无法测试返回 customException 的类

转载 作者:行者123 更新时间:2023-12-01 11:08:09 24 4
gpt4 key购买 nike

在试验 JUnit 时,我尝试测试一个简单的私有(private)方法,如下所示,该方法接收一个字符串并确保它不包含“Dummy”一词。

我知道,可以将测试放在与类相同的包中,并更改要打包的方法的访问修饰符,但我想使用反射来了解这一点。

private void validateString(String myString) throws CustomException {

if (myString.toLowerCase().matches(".*dummy.*"))
throw new CustomException("String has the invalid word!");

}

我尝试通过反射访问私有(private)方法,但测试失败!它显示以下异常:

java.lang.AssertionError:Expected test to throw
(an instance of com.myproject.exception.CustomException and exception
with message a string containing "String has the invalid word!")

基于此question的答案,我也捕获了 InitationTargetException

JUnit

    @Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldThrowExceptionForInvalidString() {

thrown.expect(CustomException.class);
thrown.expectMessage("String has the invalid word!");

try {
MyClass myCls = new MyClass();
Method valStr = myCls.getClass().getDeclaredMethod(
"validateString", String.class);
valStr.setAccessible(true);
valStr.invoke(myCls, "This is theDummyWord find it if you can.");
} catch (InvocationTargetException | NoSuchMethodException
| SecurityException | IllegalAccessException
| IllegalArgumentException n) {
if (n.getCause().getClass() == CustomException.class) {
throw new CustomException("String has the invalid word!");
}
}

}

最佳答案

我同意上面评论中的@Stultuske,并将测试重写为:

@Test
public void shouldThrowExceptionForInvalidString() {

try {
MyClass myCls = new MyClass();
Method valStr = myCls.getClass().getDeclaredMethod(
"validateString", String.class);
valStr.setAccessible(true);
valStr.invoke(myCls, "This is theDummyWord find it if you can.");
} catch (Exception e) {
assert(e instanceOf CustomException);
assert(e.getMessage.equals("String has the invalid word!"));
}

}

或者如果你想使用 ExpectedException

@Rule
public ExpectedException thrown = ExpectedException.none();

@Test
public void shouldThrowExceptionForInvalidString() {

thrown.expect(CustomException.class);
thrown.expectMessage("String has the invalid word!");

MyClass myCls = new MyClass();
Method valStr = myCls.getClass().getDeclaredMethod("validateString", String.class);
valStr.setAccessible(true);
valStr.invoke(myCls, "This is theDummyWord find it if you can.");

}

关于java - 无法测试返回 customException 的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32709784/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com