我在上面的评论中同意@Stultuske,并将测试重写为:
@Testpublic 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
@Rulepublic ExpectedException thrown = ExpectedException.none();@Testpublic 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.");}


