How to verify that an exception was not thrown

前端 未结 4 1133
天涯浪人
天涯浪人 2020-12-17 10:06

In my unit test using Mockito I want to verify that NullPointerException was not thrown.

public void testNPENotThrown{
    Calling calling= Mock         


        
4条回答
  •  不思量自难忘°
    2020-12-17 10:35

    If I dont understand you wrong you need something like this:

    @Test(expected = NullPointerException.class)
    public void testNPENotThrown {
        Calling calling= Mock(Calling .class);
        testClass.setInner(calling);
        testClass.setThrow(true);
    
        testClass.testMethod();
    
        verify(calling, never()).method();
        Assert.fail("No NPE");
    }
    

    but by the naming of the test "NPENotThrown" I would expect a test like this:

    public void testNPENotThrown {
        Calling calling= Mock(Calling .class);
        testClass.setInner(calling);
        testClass.setThrow(true);
    
        testClass.testMethod();
        try {
            verify(calling, never()).method();
            Assert.assertTrue(Boolean.TRUE);
        } catch(NullPointerException ex) {
            Assert.fail(ex.getMessage());
        }
    }
    

提交回复
热议问题