How do you assert that a certain exception is thrown in JUnit 4 tests?

前端 未结 30 1994
忘掉有多难
忘掉有多难 2020-11-21 22:23

How can I use JUnit4 idiomatically to test that some code throws an exception?

While I can certainly do something like this:

@Test
public void testFo         


        
30条回答
  •  走了就别回头了
    2020-11-21 22:59

    In my case I always get RuntimeException from db, but messages differ. And exception need to be handled respectively. Here is how I tested it:

    @Test
    public void testThrowsExceptionWhenWrongSku() {
    
        // Given
        String articleSimpleSku = "999-999";
        int amountOfTransactions = 1;
        Exception exception = null;
    
        // When
        try {
            createNInboundTransactionsForSku(amountOfTransactions, articleSimpleSku);
        } catch (RuntimeException e) {
            exception = e;
        }
    
        // Then
        shouldValidateThrowsExceptionWithMessage(exception, MESSAGE_NON_EXISTENT_SKU);
    }
    
    private void shouldValidateThrowsExceptionWithMessage(final Exception e, final String message) {
        assertNotNull(e);
        assertTrue(e.getMessage().contains(message));
    }
    

提交回复
热议问题