无法测试返回customException的类
在试验JUnit时,我试图测试一个简单的私有方法,如下所示,此方法接收一个String并确保其中不包含单词“Dummy”。
我知道,可以将测试放在与类相同的包中,并将方法的访问修饰符更改为包,但我想使用reflection来学习。
private void validateString(String myString) throws CustomException { if (myString.toLowerCase().matches(".*dummy.*")) throw new CustomException("String has the invalid word!"); }
我试图通过reflection访问私有方法,但测试失败! 它显示以下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并将测试重写为:
@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."); }