From b36b07edd1bc95e4fdeb0fc2d97c916d6d482a1d Mon Sep 17 00:00:00 2001 From: xmarek14 <xmarek14@fi.muni.cz> Date: Sun, 16 Apr 2023 22:31:05 +0200 Subject: [PATCH] All car component tests --- .../java/cz/muni/pa165/component/App.java | 7 +- .../pa165/component/config/TestConfig.java | 15 +- .../ComponentRepositoryUnitTest.java | 100 +++++++----- .../ComponentControllerIntegrationTest.java | 144 ++++++++++++++++++ .../rest/ComponentControllerItTest.java | 24 --- .../rest/ComponentControllerUnitTest.java | 141 +++++++++-------- .../component/util/ComponentTestUtil.java | 56 +++++++ 7 files changed, 359 insertions(+), 128 deletions(-) create mode 100644 component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerIntegrationTest.java delete mode 100644 component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerItTest.java create mode 100644 component/src/test/java/cz/muni/pa165/component/util/ComponentTestUtil.java diff --git a/component/src/main/java/cz/muni/pa165/component/App.java b/component/src/main/java/cz/muni/pa165/component/App.java index 8e4fee47..4e6c468a 100644 --- a/component/src/main/java/cz/muni/pa165/component/App.java +++ b/component/src/main/java/cz/muni/pa165/component/App.java @@ -6,12 +6,12 @@ import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.domain.EntityScan; import org.springframework.context.annotation.Bean; import org.springframework.data.jpa.repository.config.EnableJpaRepositories; +import org.springframework.web.client.RestTemplate; /** * Main app. */ @SpringBootApplication() -@EnableJpaRepositories(basePackages = {"cz.muni.pa165.component.data.repository"}) @EntityScan("cz.muni.pa165.component.data.model") public class App { @@ -19,4 +19,9 @@ public class App { SpringApplication.run(App.class, args); } + @Bean + public RestTemplate restTemplate() { + return new RestTemplate(); + } + } diff --git a/component/src/test/java/cz/muni/pa165/component/config/TestConfig.java b/component/src/test/java/cz/muni/pa165/component/config/TestConfig.java index 0895502b..ec59a474 100644 --- a/component/src/test/java/cz/muni/pa165/component/config/TestConfig.java +++ b/component/src/test/java/cz/muni/pa165/component/config/TestConfig.java @@ -8,7 +8,9 @@ import org.springframework.jdbc.datasource.DriverManagerDataSource; import org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean; import org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter; - +/** + * Configuration for tests. + */ @Configuration public class TestConfig { @@ -19,6 +21,11 @@ public class TestConfig { this.dataSource = dataSource(); } + /** + * Data source for factory. + * + * @return data source + */ public DataSource dataSource() { DriverManagerDataSource dataSource = new DriverManagerDataSource(); dataSource.setDriverClassName("org.h2.Driver"); @@ -28,7 +35,11 @@ public class TestConfig { return dataSource; } - + /** + * Custom entity manager factory. + * + * @return factory bean + */ @Bean public LocalContainerEntityManagerFactoryBean entityManagerFactory() { HibernateJpaVendorAdapter vendorAdapter = new HibernateJpaVendorAdapter(); diff --git a/component/src/test/java/cz/muni/pa165/component/repository/ComponentRepositoryUnitTest.java b/component/src/test/java/cz/muni/pa165/component/repository/ComponentRepositoryUnitTest.java index 53a71596..5aba00f0 100644 --- a/component/src/test/java/cz/muni/pa165/component/repository/ComponentRepositoryUnitTest.java +++ b/component/src/test/java/cz/muni/pa165/component/repository/ComponentRepositoryUnitTest.java @@ -1,17 +1,21 @@ package cz.muni.pa165.component.repository; +import static cz.muni.pa165.component.util.ComponentTestUtil.getComponent; + import cz.muni.pa165.component.data.model.CarComponent; import cz.muni.pa165.component.data.repository.ComponentRepositoryInterface; +import java.math.BigDecimal; import org.junit.Test; import org.junit.jupiter.api.Assertions; +import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; import org.springframework.boot.test.autoconfigure.orm.jpa.TestEntityManager; import org.springframework.test.context.junit4.SpringRunner; -import org.junit.runner.RunWith; - -import java.math.BigDecimal; +/** + * Unit tests for component repository. + */ @RunWith(SpringRunner.class) @DataJpaTest public class ComponentRepositoryUnitTest { @@ -24,50 +28,74 @@ public class ComponentRepositoryUnitTest { @Test public void saveTest() { - CarComponent carComponent = CarComponent.builder() - .name("name") - .weight(BigDecimal.ONE) - .price(BigDecimal.ONE) - .manufacturer("manufacturer") - .build(); + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); - CarComponent savedComponent = componentRepository.save(carComponent); + var savedComponent = componentRepository.save(carComponent); Assertions.assertEquals(savedComponent, carComponent); + Assertions.assertEquals(entityManager.find(CarComponent.class, 1L).getId(), 1); } @Test - public void findTest() { + public void findByIdTest() { + Long id = 2L; String name = "Engine"; BigDecimal one = BigDecimal.ONE; String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + + var savedComponent = componentRepository.save(carComponent); + var component = componentRepository.findById(savedComponent.getId()).orElseThrow(); + + Assertions.assertAll( + () -> Assertions.assertEquals(component.getId(), savedComponent.getId()), + () -> Assertions.assertEquals(component.getName(), savedComponent.getName()), + () -> Assertions.assertEquals(component.getPrice(), savedComponent.getPrice()), + () -> Assertions.assertEquals(component.getWeight(), savedComponent.getWeight()), + () -> Assertions.assertEquals(component.getManufacturer(), savedComponent.getManufacturer()) + ); + } + + @Test + public void findByNonExistingIdTest() { + Assertions.assertThrows(Exception.class, () -> componentRepository.findById(-1L).orElseThrow()); + } + + @Test + public void deleteByIdTest() { + Long id = 3L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + + var savedComponent = componentRepository.save(carComponent); + componentRepository.delete(savedComponent); + + Assertions.assertThrows(Exception.class, () -> componentRepository + .findById(savedComponent.getId()).orElseThrow()); + } + + @Test + public void testFindAll() { + Long id1 = 4L; + Long id2 = 5L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent1 = getComponent(id1, name, one, manufacturer); + var carComponent2 = getComponent(id2, name, one, manufacturer); + + componentRepository.save(carComponent1); + componentRepository.save(carComponent2); - CarComponent carComponent = CarComponent.builder() - .name(name) - .weight(one) - .price(one) - .manufacturer(manufacturer) - .build(); - - componentRepository.save(carComponent); - Long id = entityManager.find(CarComponent.class, 1L).getId(); - - Assertions.assertEquals( - entityManager.find(CarComponent.class, id).getId(), - id); - Assertions.assertEquals( - entityManager.find(CarComponent.class, id).getName(), - name); - Assertions.assertEquals( - entityManager.find(CarComponent.class, id).getPrice(), - one); - Assertions.assertEquals( - entityManager.find(CarComponent.class, id).getWeight(), - one); - Assertions.assertEquals( - entityManager.find(CarComponent.class, id).getManufacturer(), - manufacturer); + var components = componentRepository.findAll(); + Assertions.assertEquals(2, components.size()); } } diff --git a/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerIntegrationTest.java b/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerIntegrationTest.java new file mode 100644 index 00000000..31d5fa92 --- /dev/null +++ b/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerIntegrationTest.java @@ -0,0 +1,144 @@ +package cz.muni.pa165.component.rest; + +import static cz.muni.pa165.component.util.ComponentTestUtil.getComponent; +import static org.junit.jupiter.api.Assertions.assertAll; +import static org.junit.jupiter.api.Assertions.assertEquals; +import static org.mockito.ArgumentMatchers.anyLong; +import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; +import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import cz.muni.pa165.component.data.model.CarComponent; +import cz.muni.pa165.component.data.repository.ComponentRepositoryInterface; +import java.math.BigDecimal; +import java.util.List; +import java.util.Optional; +import org.junit.jupiter.api.Assertions; +import org.junit.jupiter.api.Test; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; +import org.springframework.boot.test.context.SpringBootTest; +import org.springframework.boot.test.mock.mockito.MockBean; +import org.springframework.http.MediaType; +import org.springframework.test.web.servlet.MockMvc; + +@SpringBootTest +@AutoConfigureMockMvc +class ComponentControllerIntegrationTest { + + @Autowired + private MockMvc mockMvc; + + @MockBean + private ComponentRepositoryInterface componentRepositoryMock; + + @Autowired + private ObjectMapper objectMapper; + + @Test + void postIntegrationTest() throws Exception { + + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + + given(componentRepositoryMock.save(carComponent)).willReturn(carComponent); + + String response = mockMvc.perform(post("/component/") + .content(objectMapper.writeValueAsString(carComponent)) + .contentType(MediaType.APPLICATION_JSON_VALUE)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + CarComponent componentResponse = objectMapper.readValue(response, CarComponent.class); + assertAll( + () -> assertEquals(carComponent.getId(), componentResponse.getId()), + () -> assertEquals(carComponent.getName(), componentResponse.getName()), + () -> assertEquals(carComponent.getWeight(), componentResponse.getWeight()), + () -> assertEquals(carComponent.getPrice(), componentResponse.getPrice()), + () -> assertEquals(carComponent.getManufacturer(), componentResponse.getManufacturer()) + ); + } + + @Test + void deleteIntegrationTest() throws Exception { + + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + + given(componentRepositoryMock.findById(anyLong())).willReturn( + Optional.of(carComponent)); + + String expectedResponse = "Car component with id: 1was successfully deleted"; + String actualResponse = mockMvc.perform(delete("/component/") + .param("componentId", String.valueOf(id)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + Assertions.assertEquals(expectedResponse, actualResponse); + } + + @Test + void getComponentByIdTest() throws Exception { + + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + + given(componentRepositoryMock.findById(id)).willReturn(Optional.of(carComponent)); + + String response = mockMvc.perform(get("/component/id") + .param("componentId", String.valueOf(id)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + var componentResponse = objectMapper.readValue(response, CarComponent.class); + + Assertions.assertAll( + () -> Assertions.assertEquals(id, componentResponse.getId()), + () -> Assertions.assertEquals(name, componentResponse.getName()), + () -> Assertions.assertEquals(one, componentResponse.getWeight()), + () -> Assertions.assertEquals(one, componentResponse.getPrice()), + () -> Assertions.assertEquals(manufacturer, componentResponse.getManufacturer()) + ); + } + + @Test + void getAllComponentsTest() throws Exception { + + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + + given(componentRepositoryMock.findAll()).willReturn(List.of(carComponent)); + + String response = mockMvc.perform(get("/component/") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + + var componentResponse = objectMapper.readValue(response, CarComponent[].class); + Assertions.assertAll( + () -> Assertions.assertEquals(id, componentResponse[0].getId()), + () -> Assertions.assertEquals(name, componentResponse[0].getName()), + () -> Assertions.assertEquals(one, componentResponse[0].getWeight()), + () -> Assertions.assertEquals(one, componentResponse[0].getPrice()), + () -> Assertions.assertEquals(manufacturer, componentResponse[0].getManufacturer()) + ); + } + +} + diff --git a/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerItTest.java b/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerItTest.java deleted file mode 100644 index 7d87f445..00000000 --- a/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerItTest.java +++ /dev/null @@ -1,24 +0,0 @@ -package cz.muni.pa165.component.rest; - -import com.fasterxml.jackson.databind.ObjectMapper; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import org.springframework.test.web.servlet.MockMvc; - -@Component -class ComponentControllerItTest { - - private static final Logger log = LoggerFactory.getLogger( - ComponentControllerUnitTest.class - ); - - @Autowired - private MockMvc mockMvc; - - @Autowired - private ObjectMapper objectMapper; - -} - diff --git a/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerUnitTest.java b/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerUnitTest.java index f27e7988..d6143263 100644 --- a/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerUnitTest.java +++ b/component/src/test/java/cz/muni/pa165/component/rest/ComponentControllerUnitTest.java @@ -1,38 +1,32 @@ package cz.muni.pa165.component.rest; +import static cz.muni.pa165.component.util.ComponentTestUtil.getComponent; +import static cz.muni.pa165.component.util.ComponentTestUtil.getComponentDto; import static org.mockito.BDDMockito.given; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.delete; +import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.jsonPath; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import com.fasterxml.jackson.databind.ObjectMapper; import cz.muni.pa165.common_library.dtos.CarComponentDto; -import cz.muni.pa165.component.config.TestConfig; import cz.muni.pa165.component.data.model.CarComponent; import cz.muni.pa165.component.service.ComponentService; import java.math.BigDecimal; +import java.util.ArrayList; +import java.util.List; +import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Test; -import org.junit.runner.RunWith; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest; import org.springframework.boot.test.mock.mockito.MockBean; -import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; -import org.springframework.test.context.ContextConfiguration; -import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; -@RunWith(SpringRunner.class) -@ContextConfiguration(classes = TestConfig.class) @WebMvcTest(ComponentController.class) class ComponentControllerUnitTest { - private static final Logger log = LoggerFactory.getLogger( - ComponentControllerUnitTest.class - ); - @Autowired private MockMvc mockMvc; @@ -42,55 +36,27 @@ class ComponentControllerUnitTest { @Autowired private ObjectMapper objectMapper; -// @Test -// void createCarComponentTest() throws Exception { -// log.debug("create carComponent"); -// -// Long id = 1L; -// String name = "Engine"; -// BigDecimal one = BigDecimal.ONE; -// String manufacturer = "Ferrari"; -// -// final String EXPECTED_JSON = "{\"id\": " + id + ", \"name\": \"" + name + "\", \"weight\": " + one + ", \"price\": " + one + ", \"manufacturer\": \"" + manufacturer + "\"}"; -// final String URL_PATH = "/component/"; -// final int EXPECTED_STATUS = HttpStatus.OK.value(); -// -// CarComponent carComponent = CarComponent.builder() -// .id(id) -// .name(name) -// .weight(one) -// .price(one) -// .manufacturer(manufacturer) -// .build(); -// -// CarComponentDto carComponentDto = CarComponentDto.builder() -// .id(id) -// .name(name) -// .weight(one) -// .price(one) -// .manufacturer(manufacturer) -// .build(); -// -// given(componentService.postCarComponent(carComponentDto)).willReturn(carComponentDto); -// -// mockMvc.perform(post(URL_PATH) -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(carComponent))) -// .andExpect(status().is(EXPECTED_STATUS)); -// -// /* -// given(componentService.postCarComponent(carComponentDto)).willReturn(carComponentDto); -// mockMvc.perform(post("/component/") -// .contentType(MediaType.APPLICATION_JSON) -// .content(objectMapper.writeValueAsString(carComponent))) -// .andExpect(status().isOk()) -// .andExpect(jsonPath("$.id").value(id)) -// .andExpect(jsonPath("$.name").value(name)) -// .andExpect(jsonPath("$.weight").value(one)) -// .andExpect(jsonPath("$.price").value(one)) -// .andExpect(jsonPath("$.manufacturer").value(manufacturer)); -// */ -// } + @Test + void createCarComponentTest() throws Exception { + + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponent = getComponent(id, name, one, manufacturer); + var carComponentDto = getComponentDto(id, name, one, manufacturer); + + given(componentService.postCarComponent(carComponentDto)).willReturn(carComponentDto); + mockMvc.perform(post("/component/") + .contentType(MediaType.APPLICATION_JSON) + .content(objectMapper.writeValueAsString(carComponent))) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(id)) + .andExpect(jsonPath("$.name").value(name)) + .andExpect(jsonPath("$.price").value(one)) + .andExpect(jsonPath("$.weight").value(one)) + .andExpect(jsonPath("$.manufacturer").value(manufacturer)); + } @Test void nonExistingPathTest() throws Exception { @@ -100,7 +66,6 @@ class ComponentControllerUnitTest { @Test void createComponentWithNullValuesTest() throws Exception { - log.debug("create invalid engine"); CarComponent carComponent = new CarComponent(); CarComponentDto carComponentDto = new CarComponentDto(); @@ -108,8 +73,54 @@ class ComponentControllerUnitTest { given(componentService.postCarComponent(carComponentDto)).willReturn(carComponentDto); mockMvc.perform(post("/component/").contentType(MediaType.APPLICATION_JSON) .content(objectMapper.writeValueAsString(carComponent))) - // .andExpect(status().isBadRequest()); - .andExpect(status().isNotFound()); + .andExpect(status().isBadRequest()); + } + + @Test + void deleteCarComponentTest() throws Exception { + + Long id = 1L; + + String expectedResponse = "Car component with id: 1was successfully deleted"; + given(componentService.deleteById(id)).willReturn(expectedResponse); + String actualResponse = mockMvc.perform(delete("/component/") + .param("componentId", String.valueOf(id)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andReturn().getResponse().getContentAsString(); + Assertions.assertEquals(expectedResponse, actualResponse); + } + + @Test + void getCarComponentTest() throws Exception { + + Long id = 1L; + String name = "Engine"; + BigDecimal one = BigDecimal.ONE; + String manufacturer = "Ferrari"; + var carComponentDto = getComponentDto(id, name, one, manufacturer); + + given(componentService.getCarComponentById(id)).willReturn(carComponentDto); + mockMvc.perform(get("/component/id") + .param("componentId", String.valueOf(id)) + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()) + .andExpect(jsonPath("$.id").value(id)) + .andExpect(jsonPath("$.name").value(name)) + .andExpect(jsonPath("$.price").value(one)) + .andExpect(jsonPath("$.weight").value(one)) + .andExpect(jsonPath("$.manufacturer").value(manufacturer)); + } + + @Test + void getAllCarComponentsTest() throws Exception { + + List<CarComponentDto> components = new ArrayList<>(); + + given(componentService.getAllCarComponents()).willReturn(components); + mockMvc.perform(get("/component/") + .contentType(MediaType.APPLICATION_JSON)) + .andExpect(status().isOk()); } } diff --git a/component/src/test/java/cz/muni/pa165/component/util/ComponentTestUtil.java b/component/src/test/java/cz/muni/pa165/component/util/ComponentTestUtil.java new file mode 100644 index 00000000..db22d0d5 --- /dev/null +++ b/component/src/test/java/cz/muni/pa165/component/util/ComponentTestUtil.java @@ -0,0 +1,56 @@ +package cz.muni.pa165.component.util; + +import cz.muni.pa165.common_library.dtos.CarComponentDto; +import cz.muni.pa165.component.data.model.CarComponent; +import java.math.BigDecimal; + +/** + * Helper class for creating Component objects. + */ +public class ComponentTestUtil { + + /** + * Returns a CarComponent instance initialized with the given parameters. + * + * @param id the ID of the car component + * @param name the name of the car component + * @param decimal the weight and price of the car component + * @param manufacturer the manufacturer of the car component + * @return a CarComponent instance initialized with the given parameters + */ + public static CarComponent getComponent(Long id, + String name, + BigDecimal decimal, + String manufacturer) { + return CarComponent.builder() + .id(id) + .name(name) + .weight(decimal) + .price(decimal) + .manufacturer(manufacturer) + .build(); + } + + /** + * Returns a CarComponentDto instance initialized with the given parameters. + * + * @param id the ID of the car component + * @param name the name of the car component + * @param decimal the weight and price of the car component + * @param manufacturer the manufacturer of the car component + * @return a CarComponentDto instance initialized with the given parameters + */ + public static CarComponentDto getComponentDto(Long id, + String name, + BigDecimal decimal, + String manufacturer) { + return CarComponentDto.builder() + .id(id) + .name(name) + .weight(decimal) + .price(decimal) + .manufacturer(manufacturer) + .build(); + } + +} -- GitLab