无法测试返回customException的类 [英] Cannot test a class that return a customException
问题描述
在尝试JUnit时,我试图测试一个简单的私有方法,如下所示,此方法接收一个String并确保其中不包含单词'Dummy'。
While experimenting JUnit, I am trying to test a simple private method as follows, this method receives a String and make sure it does not include the word 'Dummy' in it.
我知道,可以将测试放在与类相同的包中,并将方法的访问修饰符更改为包,但我想使用反射来学习。
I know, it is possible to put the test in the same package as the class and change access modifier of the method to package but I would like to use reflection to learn that.
private void validateString(String myString) throws CustomException {
if (myString.toLowerCase().matches(".*dummy.*"))
throw new CustomException("String has the invalid word!");
}
我试图通过反射访问私有方法但是测试失败!它显示以下异常:
I am trying to access the private method through reflection but the test fails! It shows following exception:
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!")
根据问题的回答,我抓了 InvocationTargetException
。
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并将测试重写为:
I agree with @Stultuske in the comments above and would rewrite the test to:
@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
Or if you want to use 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.");
}
这篇关于无法测试返回customException的类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!