Mockito How to mock and assert a thrown exception?

后端 未结 11 1257
既然无缘
既然无缘 2020-12-02 05:45

I\'m using mockito in a junit test. How do you make an exception happen and then assert that it has (generic pseudo-code)

11条回答
  •  天命终不由人
    2020-12-02 06:48

    Or if your exception is thrown from the constructor of a class:

    @Rule
    public ExpectedException exception = ExpectedException.none();
    
    @Test
    public void myTest() {    
    
        exception.expect(MyException.class);
        CustomClass myClass= mock(CustomClass.class);
        doThrow(new MyException("constructor failed")).when(myClass);  
    
    }
    

提交回复
热议问题