Cannot test a class that return a customException

前端 未结 1 1593
無奈伤痛
無奈伤痛 2021-01-26 04:46

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.

相关标签:
1条回答
  • 2021-01-26 05:15

    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!"));
        }
    
    }
    

    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.");
    
    }
    
    0 讨论(0)
提交回复
热议问题