Skip to content

Application Test Suite with JUnit 5 & Mockito 🍸

Lyes S edited this page Jan 2, 2022 · 1 revision

Table Of Contents

Repository

Repository Integration Tests

@DataJpaTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NetworkDeviceRepositoryIntegrationTest {

    @Autowired
    private INetworkDeviceRepository networkDeviceRepository;

    private NetworkDevice networkDevice;

    @BeforeEach
    void setUp() {
        // given
        networkDevice = NetworkDevice.builder()
                .ipAddress("10.133.10.20")
                .elementType(ElementType.LAPTOP)
                .connections(new HashSet<>())
                .build();
    }

    @Test
    @Order(1)
    @DisplayName("CREATE Network Device")
    @Rollback(value = false)
    public void testSave() {
        // given networkDevice
        // when
        NetworkDevice savedNetworkDevice = networkDeviceRepository.save(networkDevice);
        // then
        assertEquals(savedNetworkDevice, networkDevice);
    }

    @Test
    @Order(2)
    @DisplayName("READ Network Devices")
    public void testGetAll() {
        // given existing sql data + previous save ~ 9 networkDeviceDto

        // when
        List<NetworkDevice> networkDevices = networkDeviceRepository.findAll();
        // then
        assertEquals(networkDevices.size(), 9);
    }

    @Test
    @Order(3)
    @DisplayName("READ Network Device")
    public void testGet() {
        // given existing sql data + previous save ~ 9 networkDeviceDto

        // when
        NetworkDevice existingNetworkDevice = networkDeviceRepository.findById(networkDevice.getIpAddress()).orElse(null);
        // then
        assertEquals(existingNetworkDevice, networkDevice);
    }

    @Test
    @Order(4)
    @DisplayName("UPDATE Network Device")
    public void testUpdate() {
        // given existing sql data + previous save ~ 9 networkDeviceDto
        networkDevice.setElementType(ElementType.SERVER);
        // when
        NetworkDevice updatedNetworkDevice = networkDeviceRepository.save(networkDevice);
        // then
        assertEquals(updatedNetworkDevice, networkDevice);
    }

    @Test
    @Order(5)
    @DisplayName("DELETE Network Device")
    public void testDelete() {
        // given existing sql data + previous save ~ 9 networkDeviceDto

        // when
        networkDeviceRepository.delete(networkDevice);
        // then
        assertEquals(networkDeviceRepository.count(), 8);
    }
}

Service

Service Unit Tests

@ExtendWith(MockitoExtension.class)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NetworkDeviceServiceUnitTest {

    @Mock
    private INetworkDeviceRepository networkDeviceRepository;

    @Spy
    private ModelMapper modelMapper;

    @InjectMocks
    private NetworkDeviceService networkDeviceService;

    private NetworkDevice networkDevice;

    @BeforeEach
    void setUp() {
        networkDevice = NetworkDevice.builder()
                .ipAddress("10.133.10.20")
                .elementType(ElementType.LAPTOP)
                .connections(new HashSet<>())
                .build();
    }

    @Test
    @Order(1)
    @DisplayName("CREATE Network Device")
    public void testSave() {
        // Given networkDevice

        // When
        when(networkDeviceRepository.save(any(NetworkDevice.class))).thenReturn(networkDevice);

        // Save NetworkDevice
        NetworkDeviceDto networkDeviceDto = networkDeviceService.save(modelMapper.toDto(networkDevice));

        // Then
        assertNotNull(networkDeviceDto);
        assertEquals("10.133.10.20", networkDeviceDto.getAddress());
        assertEquals(ElementType.LAPTOP.getValue(), networkDeviceDto.getElementType());
        assertEquals(0, networkDeviceDto.getNeighbors().size());
    }

    @Test
    @Order(2)
    @DisplayName("READ Network Device")
    public void testFindById() {
        // Given networkDevice

        // When
        when(networkDeviceRepository.findById(networkDevice.getIpAddress())).thenReturn(Optional.of(networkDevice));

        // Find NetworkDevice By Id
        NetworkDeviceDto networkDeviceDto = networkDeviceService.findById(networkDevice.getIpAddress());

        // Then
        assertNotNull(networkDeviceDto);
        assertEquals("10.133.10.20", networkDeviceDto.getAddress());
        assertEquals(ElementType.LAPTOP.getValue(), networkDeviceDto.getElementType());
        assertEquals(0, networkDeviceDto.getNeighbors().size());
    }


    @Test
    @Order(3)
    @DisplayName("UPDATE Network Device")
    public void testUpdate() {
        // Given networkDevice
        networkDevice.setElementType(ElementType.SWITCH);

        // When
        when(networkDeviceRepository.save(networkDevice)).thenReturn(networkDevice);
        when(networkDeviceRepository.findById(networkDevice.getIpAddress())).thenReturn(Optional.of(networkDevice));

        // Update NetworkDevice
        NetworkDeviceDto updatedNetworkDeviceDto = networkDeviceService.update(modelMapper.toDto(networkDevice), networkDevice.getIpAddress());

        // Then
        assertNotNull(updatedNetworkDeviceDto);
        assertEquals(updatedNetworkDeviceDto.getElementType(), networkDevice.getElementType().getValue());
    }

    @Test
    @Order(4)
    @DisplayName("DELETE Network Device")
    public void testDelete() {
        // Given networkDevice

        // When
        when(networkDeviceRepository.findById(networkDevice.getIpAddress())).thenReturn(Optional.of(networkDevice));
        doNothing().when(networkDeviceRepository).delete(networkDevice);

        // Delete NetworkDevice
        networkDeviceService.delete(networkDevice.getIpAddress());

        // Then
        verify(networkDeviceRepository, times(1)).delete(networkDevice);
    }

    @Test
    @Order(5)
    @DisplayName("EXCEPTION NetworkDeviceNotFoundException")
    public void testThrowExceptionFindById() {
        // Given networkDevice

        // When
        when(networkDeviceRepository.findById(networkDevice.getIpAddress())).thenReturn(Optional.ofNullable(null));

        // Then
        assertThrows(NetworkDeviceNotFoundException.class, () -> networkDeviceService.findById(networkDevice.getIpAddress()));
    }
}

Service Integration Tests

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.NONE)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
public class NetworkDeviceServiceIntegrationTest {

    private final IService<NetworkDeviceDto> networkDeviceService;

    private final INetworkDeviceRepository networkDeviceRepository;

    private NetworkDeviceDto networkDeviceDto;

    @Autowired
    public NetworkDeviceServiceIntegrationTest(IService<NetworkDeviceDto> networkDeviceService, INetworkDeviceRepository networkDeviceRepository) {
        this.networkDeviceService = networkDeviceService;
        this.networkDeviceRepository = networkDeviceRepository;
    }


    @BeforeEach
    void setUp() {
        // given
         networkDeviceDto = NetworkDeviceDto.builder()
                .address("10.133.10.20")
                .elementType(ElementType.LAPTOP.getValue())
                .neighbors(new HashSet<>())
                .build();
    }

    @Test
    @Order(1)
    @DisplayName("CREATE Network Device")
    public void testSave() {
        // given networkDeviceDto
        // when
        NetworkDeviceDto savedNetworkDeviceDto = networkDeviceService.save(networkDeviceDto);
        // then
        assertNotNull(savedNetworkDeviceDto);
        assertEquals(networkDeviceDto, savedNetworkDeviceDto);
    }

    @Test
    @Order(2)
    @DisplayName("READ Network Device")
    public void testFindById() {
        // given
        String id = "10.133.10.20";
        // when
        NetworkDeviceDto savedNetworkDeviceDto = networkDeviceService.findById(id);
        // then
        assertNotNull(savedNetworkDeviceDto);
        assertEquals(id, savedNetworkDeviceDto.getAddress());
    }

    @Test
    @Order(3)
    @DisplayName("UPDATE Network Device")
    public void testUpdate() {
        // given
        networkDeviceDto.setElementType(ElementType.SWITCH.getValue());
        // when
        NetworkDeviceDto updatedNetworkDeviceDto = networkDeviceService.update(networkDeviceDto, "10.133.10.20");
        // then
        assertNotNull(updatedNetworkDeviceDto);
        assertEquals(networkDeviceDto, updatedNetworkDeviceDto);
    }


    @Test
    @Order(4)
    @DisplayName("DELETE Network Device")
    public void testDelete() {
        // given networkDeviceDto
        // when
        networkDeviceService.delete("10.133.10.20");
        // then
        assertThrows(NetworkDeviceNotFoundException.class, () -> networkDeviceService.findById(networkDeviceDto.getAddress()));
    }


}

Controller

Controller Unit Tests

@WebMvcTest
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
class NetworkDeviceControllerUnitTest {

    @MockBean
    private IService<NetworkDeviceDto> networkDeviceService;

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    private  NetworkDeviceDto networkDeviceDto;

    @BeforeEach
    void setUp() {
        // given
        networkDeviceDto = NetworkDeviceDto.builder()
                .address("10.133.10.20")
                .elementType(ElementType.LAPTOP.getValue())
                .neighbors(new HashSet<>())
                .build();
    }

    @Test
    @Order(1)
    @DisplayName("CREATE Network Device")
    public void testSave() throws Exception {
        // given networkDeviceDto

        // when
        when(networkDeviceService.save(networkDeviceDto)).thenReturn(networkDeviceDto);

        // then
        mockMvc.perform(post("/v1/network-devices")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(networkDeviceDto)))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.address").value(networkDeviceDto.getAddress()))
                .andExpect(jsonPath("$.elementType").value(networkDeviceDto.getElementType()))
                .andExpect(jsonPath("$.neighbors").isArray())
                .andExpect(jsonPath("$.neighbors", hasSize(0)));

    }

    @Test
    @Order(2)
    @DisplayName("READ Network Devices")
    public void testGetAll() throws Exception {
        // given existing sql data + previous POST ~ 9 networkDeviceDto

        // when
        when(networkDeviceService.findAll()).thenReturn(Arrays.asList(networkDeviceDto));

        // then
        mockMvc.perform(get("/v1/network-devices")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.size()", is(1)));

    }

    @Test
    @Order(3)
    @DisplayName("READ Network Device")
    public void testGet() throws Exception {
        // given networkDeviceDto

        // when
        when(networkDeviceService.findById(networkDeviceDto.getAddress())).thenReturn(networkDeviceDto);

        // then
        mockMvc.perform(get("/v1/network-devices/{id}", "10.133.10.20")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.address").value(networkDeviceDto.getAddress()))
                .andExpect(jsonPath("$.elementType").value(networkDeviceDto.getElementType()))
                .andExpect(jsonPath("$.neighbors").isArray())
                .andExpect(jsonPath("$.neighbors", hasSize(0)));
    }

    @Test
    @Order(4)
    @DisplayName("UPDATE Network Device")
    public void testPut() throws Exception {
        // given networkDeviceDto
        networkDeviceDto.setElementType(ElementType.DESKTOP_COMPUTER.getValue());

        // when
        when(networkDeviceService.update(networkDeviceDto, networkDeviceDto.getAddress())).thenReturn(networkDeviceDto);

        // then
        mockMvc.perform(put("/v1/network-devices/{id}", "10.133.10.20")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(networkDeviceDto)))
                .andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.address").value("10.133.10.20"))
                .andExpect(jsonPath("$.elementType").value(ElementType.DESKTOP_COMPUTER.getValue()))
                .andExpect(jsonPath("$.neighbors", hasSize(0)));
    }

    @Test
    @Order(5)
    @DisplayName("DELETE Network Device")
    public void testDelete() throws Exception {
        // given networkDeviceDto

        // when
        doNothing().when(networkDeviceService).delete(networkDeviceDto.getAddress());

        // then
        mockMvc.perform(delete("/v1/network-devices/{id}", "10.133.10.20")
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isOk())
                .andDo(result -> verify(networkDeviceService, times(1)).delete(networkDeviceDto.getAddress()));
    }

    @Test
    @Order(6)
    @DisplayName("EXCEPTION NetworkDeviceNotFoundException")
    public void testThrowNotFoundException() throws Exception {
        // given
        String networkDeviceId = "10.133.13.255";

        // when
        when(networkDeviceService.findById(networkDeviceId)).thenThrow(NetworkDeviceNotFoundException.class);

        // then
        mockMvc.perform(get("/v1/network-devices/{id}", networkDeviceId)
                .contentType(MediaType.APPLICATION_JSON))
                .andDo(print())
                .andExpect(status().isNotFound())
                .andExpect(result -> assertTrue(result.getResolvedException() instanceof NetworkDeviceNotFoundException));
    }

}

Controller Integration Tests

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@TestMethodOrder(MethodOrderer.OrderAnnotation.class)
@AutoConfigureMockMvc
public class NetworkDeviceControllerIntegrationTest {

    @Autowired
    private MockMvc mockMvc;

    @Autowired
    private ObjectMapper objectMapper;

    private  NetworkDeviceDto networkDeviceDto;


    @BeforeEach
    void setUp() {
        // given
         networkDeviceDto = NetworkDeviceDto.builder()
                .address("10.133.10.20")
                .elementType(ElementType.LAPTOP.getValue())
                .neighbors(new HashSet<>())
                .build();
    }


    @Test
    @Order(1)
    @DisplayName("CREATE Network Device")
    public void testSave() throws Exception {
        // given networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(post("/v1/network-devices")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(networkDeviceDto)));

        // then
        resultActions.andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.address").value(networkDeviceDto.getAddress()))
                .andExpect(jsonPath("$.elementType").value(networkDeviceDto.getElementType()))
                .andExpect(jsonPath("$.neighbors").isArray())
                .andExpect(jsonPath("$.neighbors", hasSize(0)));

    }

    @Test
    @Order(2)
    @DisplayName("READ Network Devices")
    public void testGetAll() throws Exception {
        // given existing sql data + previous POST ~ 9 networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(get("/v1/network-devices")
                .contentType(MediaType.APPLICATION_JSON));

        // then
        resultActions.andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.size()", is(9)));

    }

    @Test
    @Order(3)
    @DisplayName("READ Network Device")
    public void testGet() throws Exception {
        // given existing sql data + previous POST ~ 9 networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(get("/v1/network-devices/{id}", "10.133.13.12")
                .contentType(MediaType.APPLICATION_JSON));

        // then
        resultActions.andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.address").value("10.133.13.12"))
                .andExpect(jsonPath("$.elementType").value("router"))
                .andExpect(jsonPath("$.neighbors", hasSize(3)));
    }

    @Test
    @Order(4)
    @DisplayName("UPDATE Network Device")
    public void testPut() throws Exception {
        // given networkDeviceDto
        networkDeviceDto.setElementType(ElementType.DESKTOP_COMPUTER.getValue());

        // when
        ResultActions resultActions = mockMvc.perform(put("/v1/network-devices/{id}", "10.133.10.20")
                .contentType(MediaType.APPLICATION_JSON)
                .content(objectMapper.writeValueAsBytes(networkDeviceDto)));

        // then
        resultActions.andDo(print())
                .andExpect(status().isOk())
                .andExpect(jsonPath("$.address").value("10.133.10.20"))
                .andExpect(jsonPath("$.elementType").value(ElementType.DESKTOP_COMPUTER.getValue()))
                .andExpect(jsonPath("$.neighbors", hasSize(0)));
    }

    @Test
    @Order(5)
    @DisplayName("DELETE Network Device")
    public void testDelete() throws Exception {
        // given networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(delete("/v1/network-devices/{id}", "10.133.10.20")
                .contentType(MediaType.APPLICATION_JSON));

        // then
        resultActions.andDo(print())
                .andExpect(status().isOk());
    }

    @Test
    @Order(6)
    @DisplayName("EXCEPTION NetworkDeviceNotFoundException")
    public void testThrowNotFoundException() throws Exception {
        // given existing sql data + previous POST ~ 9 networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(get("/v1/network-devices/{id}", "10.133.13.255")
                .contentType(MediaType.APPLICATION_JSON));

        // then
        resultActions.andDo(print())
                .andExpect(status().isNotFound())
                .andExpect(result -> assertTrue(result.getResolvedException() instanceof NetworkDeviceNotFoundException));
    }

    @Test
    @Order(7)
    @DisplayName("EXCEPTION HttpRequestMethodNotSupportedException")
    public void testThrowHttpRequestMethodNotSupportedException() throws Exception {
        // given networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(patch("/v1/network-devices/{id}", "10.133.10.20")
                .contentType(MediaType.APPLICATION_JSON));

        // then
        resultActions.andDo(print())
                .andExpect(status().isNotFound())
                .andExpect(result -> assertTrue(result.getResolvedException() instanceof HttpRequestMethodNotSupportedException));
    }

    @Test
    @Order(8)
    @DisplayName("EXCEPTION HttpMediaTypeNotSupportedException")
    public void testThrowHttpMediaTypeNotSupportedException() throws Exception {
        // given networkDeviceDto

        // when
        ResultActions resultActions = mockMvc.perform(get("/v1/network-devices")
                .contentType(MediaType.APPLICATION_XHTML_XML));

        // then
        resultActions.andDo(print())
                .andExpect(status().isUnsupportedMediaType())
                .andExpect(result -> assertTrue(result.getResolvedException() instanceof HttpMediaTypeNotSupportedException));
    }


}

Test Suite

@Suite
@SelectPackages({"com.lyess.network_device_inventory.controller",
        "com.lyess.network_device_inventory.service",
        "com.lyess.network_device_inventory.repository"})
@SuiteDisplayName("NetworkDeviceInventoryApplicationTestSuite")
class NetworkDeviceInventoryApplicationTests {

}

mitsuke ( β—₯β—£_β—’β—€ ) : ~/eclipse-workspace/network-device-inventory$ mvn clean test

[INFO] Results:
[INFO]
[INFO] Tests run: 28, Failures: 0, Errors: 0, Skipped: 0
[INFO]
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESS
[INFO] ------------------------------------------------------------------------
[INFO] Total time:  19.060 s
[INFO] Finished at: 2022-01-02T11:10:02-05:00
[INFO] ------------------------------------------------------------------------
Clone this wiki locally