无法测试返回customException的类

时间:2015-09-22 06:25:17

标签: java reflection junit

在尝试JUnit时,我尝试按如下方式测试一个简单的私有方法,此方法接收一个String并确保其中不包含单词“Dummy”。

我知道,可以将测试放在与类相同的包中,并将方法的访问修饰符更改为包,但我想使用反射来学习。

private void validateString(String myString) throws CustomException {

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

}

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

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的答案,我也抓住了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!");
            }
        }

    }

1 个答案:

答案 0 :(得分:1)

我同意上述评论中的@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.");

}