Search code examples
spring-bootamazon-dynamodbjunit5spring-boot-test

Handling multiple exception using JUNIT5 test cases


I have created a JUNIT test case for my DynamoDB CRUD operation. I have used assertions to handle the unexpected exception giver in below code.

@Test
void createItemsInTable() throws Exception {

    Assertions.assertThrows(UnexpectedException.class, () -> {

        ResponseEntity Res;

        CatalogItems cat = new CatalogItems(3, "", "fghsdfh");

        Res = Eservice.createItemInDynamoDbTable(cat);

        System.out.println(Res.getStatusCodeValue());

        CatalogItems cat2 = Eservice.findById("3");

        assertEquals(Res.getStatusCodeValue(), 201);

        assertEquals(cat2.getTitle(), cat.getTitle());

        assertEquals(cat2.getAuthor(), cat.getAuthor());

        assertEquals(cat2.getId(), cat.getId());

    });

}

How should i specify multiple exceptions in above JUNIT test case for ex: UnexpectedException, ResourceNotFoundException etc...


Solution

  • I'd separate the three different scenarios into test cases of their own. Similar to that:

    @Test
    void updateItem() throws Exception {
        CatalogItems cat = new CatalogItems(1, "xxxx", "f");
    
        ResponseEntity Res = Eservice.updateItemInDynamoDbTable(cat);
    
        System.out.println(Res.getStatusCodeValue());
    
        CatalogItems cat2 = Eservice.findById("1");
    
        assertEquals(Res.getStatusCodeValue(), 201);
    
        assertEquals(cat2.getAuthor(), cat.getAuthor());
    
        assertEquals(cat2.getTitle(), cat.getTitle());
    
        assertEquals(cat2.getId(), cat.getId());
    }
    
    @Test
    void updateItemFailsWhenDestinationIsNotFound() {
        CatalogItems cat = new CatalogItems(3, "xxx", "xxx");
    
        Exception exception = assertThrows(ResourceNotFoundException.class, () -> {
            ResponseEntity Res = Eservice.updateItemInDynamoDbTable(cat);
        });
    
        String expectedMessage = "ResourceNotFoundException";
    
        String actualMessage = exception.getMessage();
    
        assertTrue(actualMessage.contains(expectedMessage));
    }
    
    @Test
    void updateItemFailsWhenIdIsNotAvailableAtDestination() {
        CatalogItems cat = new CatalogItems(3, "xxx", "xxx");
    
        Exception exception = assertThrows(NullPointerException.class, () -> {
            ResponseEntity Res = Eservice.updateItemInDynamoDbTable(cat);
        });
    
        System.out.println(exception.getMessage());
    
        assertNull(exception.getMessage());
    }
    

    It's good practice to have only the code that actually throws the exception in he assertThrows lambda. That way you can be sure it's this code that fails.

    I'd also recommend to stick with Java's naming convention, i.e. have members, variables and parameters in lower camel case.