Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Repository and controller tests #12

Merged
merged 5 commits into from
Mar 31, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ public Operation customize(Operation operation, HandlerMethod handlerMethod) {
if (preAuthorizeAnnotation != null
&& preAuthorizeAnnotation.value().contains("ROLE_")) {
String description = operation.getDescription() == null
? "" : (operation.getDescription()/* + "\n"*/);
? "" : (operation.getDescription());
int firstBraceIndex = preAuthorizeAnnotation.value().indexOf('(');
int lastBraceIndex = preAuthorizeAnnotation.value().lastIndexOf(')');
String rolesString = preAuthorizeAnnotation.value()
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
import jakarta.persistence.criteria.Path;
import java.util.Arrays;
import mate.academy.carsharing.model.Payment;
import mate.academy.carsharing.model.Rental;
import mate.academy.carsharing.model.User;
import mate.academy.carsharing.repository.SpecificationProvider;
import org.springframework.data.jpa.domain.Specification;
Expand All @@ -17,7 +18,8 @@ public String getKey() {

public Specification<Payment> getSpecification(String[] params) {
return (root, query, criteriaBuilder) -> {
Path<User> userPath = root.get("user");
Path<Rental> rentalPath = root.get("rental");
Path<User> userPath = rentalPath.get("user");
Path<Long> idPath = userPath.get("id");
return idPath.in(Arrays.stream(params).toArray());
};
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@
public class StripePaymentServiceImpl implements PaymentService {
private static final BigDecimal CONVERT_TO_CENT = BigDecimal.valueOf(100L);
private static final BigDecimal FINE_MULTIPLIER = BigDecimal.valueOf(1.50);

private final PaymentRepository paymentRepository;
private final PaymentMapper paymentMapper;
private final RentalRepository rentalRepository;
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,225 @@
package mate.academy.carsharing.controller;

import static mate.academy.carsharing.util.TestUtils.UPDATED_BRAND;
import static mate.academy.carsharing.util.TestUtils.UPDATED_MODEL;
import static mate.academy.carsharing.util.TestUtils.VALID_DAILY_FEE;
import static mate.academy.carsharing.util.TestUtils.VALID_ID;
import static mate.academy.carsharing.util.TestUtils.VALID_INVENTORY;
import static mate.academy.carsharing.util.TestUtils.VALID_LARGE_ID_1234567;
import static mate.academy.carsharing.util.TestUtils.createAudiQ5CarResponseDto;
import static mate.academy.carsharing.util.TestUtils.createBmwX5CarResponseDto;
import static mate.academy.carsharing.util.TestUtils.createValidCarRequestDto;
import static mate.academy.carsharing.util.TestUtils.createValidCarResponseDto;
import static org.assertj.core.api.Assertions.assertThat;
import static org.springframework.security.test.web.servlet.setup.SecurityMockMvcConfigurers.springSecurity;
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.request.MockMvcRequestBuilders.put;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.List;
import javax.sql.DataSource;
import mate.academy.carsharing.dto.car.CarResponseDto;
import mate.academy.carsharing.dto.car.CreateCarRequestDto;
import mate.academy.carsharing.model.Car;
import org.junit.jupiter.api.AfterAll;
import org.junit.jupiter.api.AfterEach;
import org.junit.jupiter.api.BeforeAll;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.TestInstance;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.core.io.ClassPathResource;
import org.springframework.http.MediaType;
import org.springframework.jdbc.datasource.init.ScriptUtils;
import org.springframework.security.test.context.support.WithMockUser;
import org.springframework.test.context.jdbc.Sql;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.test.web.servlet.MvcResult;
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
import org.springframework.web.context.WebApplicationContext;

@TestInstance(TestInstance.Lifecycle.PER_CLASS)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class CarControllerIntegrationTest {
private MockMvc mockMvc;
@Autowired
private ObjectMapper objectMapper;
@Autowired
private DataSource dataSource;
@Autowired
private WebApplicationContext applicationContext;

@BeforeAll
void beforeAll() throws SQLException {
mockMvc = MockMvcBuilders
.webAppContextSetup(applicationContext)
.apply(springSecurity())
.build();
teardown();
}

@AfterAll
void afterAll() throws SQLException {
setupDatabase(dataSource);
}

@BeforeEach
public void beforeEach() throws SQLException {
setupDatabase(dataSource);
}

@AfterEach
public void afterEach() throws SQLException {
teardown();
}

private void teardown() throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(true);
ScriptUtils.executeSqlScript(
connection,
new ClassPathResource("sql/controller/cars/clear-cars-table.sql")
);
}
}

private void setupDatabase(DataSource dataSource) throws SQLException {
try (Connection connection = dataSource.getConnection()) {
connection.setAutoCommit(true);
ScriptUtils.executeSqlScript(
connection,
new ClassPathResource("sql/controller/cars/fill-cars-table.sql")
);
}
}

@Test
@DisplayName("create() method works")
@WithMockUser(username = "manager@mail.com", roles = {"MANAGER"})
public void create_WithValidCreateCarRequestDto_ReturnValidCarResponseDto() throws Exception {
CreateCarRequestDto createCarRequestDto = createValidCarRequestDto();
CarResponseDto expected = createValidCarResponseDto();
String jsonRequest = objectMapper.writeValueAsString(createCarRequestDto);

MvcResult mvcResult = mockMvc.perform(
post("/api/cars")
.content(jsonRequest)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isCreated())
.andReturn();

CarResponseDto actual = objectMapper
.readValue(mvcResult.getResponse().getContentAsString(), CarResponseDto.class);

assertThat(actual.getModel()).isNotNull();
assertThat(actual.getModel()).isEqualTo(expected.getModel());
}

@Test
@WithMockUser(username = "manager@mail.com", roles = {"MANAGER"})
@DisplayName("deleteById() method works")
public void deleteById_WithValidId_ReturnNoContentStatus() throws Exception {
mockMvc.perform(
delete("/api/cars/{id}", VALID_ID)
)
.andExpect(status().isNoContent())
.andReturn();
}

@Test
@WithMockUser(username = "john@mail.com", roles = {"CUSTOMER"})
@DisplayName("getAll() method returns all cars")
public void getAll_WithValidParam_ReturnListWithAllCars() throws Exception {
CarResponseDto audiCar = createAudiQ5CarResponseDto();
CarResponseDto bmwCar = createBmwX5CarResponseDto();
List<CarResponseDto> expected = List.of(audiCar, bmwCar);

MvcResult mvcResult = mockMvc.perform(
get("/api/cars")
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andReturn();

String jsonResponse = mvcResult.getResponse().getContentAsString();
List<CarResponseDto> actual = objectMapper.readValue(jsonResponse,
new TypeReference<>() {
});

assertThat(actual)
.usingRecursiveComparison()
.ignoringFields("id")
.isEqualTo(expected);
}

@Sql(
scripts = "classpath:sql/controller/cars/add-default_valid-car.sql",
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
@Test
@WithMockUser(username = "john@mail.com", roles = {"CUSTOMER"})
@DisplayName("getById() method returns car with specified id")
public void getById_WithValidId_ReturnValidCarResponseDto() throws Exception {
CarResponseDto expected = createValidCarResponseDto(VALID_LARGE_ID_1234567);

MvcResult mvcResult = mockMvc.perform(
get("/api/cars/{id}", VALID_LARGE_ID_1234567)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andReturn();

String jsonResponse = mvcResult.getResponse().getContentAsString();
CarResponseDto actual = objectMapper
.readValue(jsonResponse, CarResponseDto.class);

assertThat(actual).isEqualTo(expected);
}

@Sql(
scripts = "classpath:sql/controller/cars/add-default_valid-car.sql",
executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD
)
@Test
@WithMockUser(username = "manager@mail.com", roles = {"MANAGER"})
@DisplayName("updateById() method updates car by specified id")
public void updateById_WithValidIdAndRequestDto_ReturnValidCarResponseDto() throws Exception {
CreateCarRequestDto updateCarRequestDto = new CreateCarRequestDto(
UPDATED_MODEL,
UPDATED_BRAND,
Car.Type.SEDAN,
VALID_INVENTORY,
VALID_DAILY_FEE
);
CarResponseDto expected = new CarResponseDto();
expected.setId(VALID_LARGE_ID_1234567);
expected.setModel(UPDATED_MODEL);
expected.setBrand(UPDATED_BRAND);
expected.setType(Car.Type.SEDAN);
expected.setInventory(VALID_INVENTORY);
expected.setDailyFee(VALID_DAILY_FEE);

String jsonRequest = objectMapper.writeValueAsString(updateCarRequestDto);
MvcResult mvcResult = mockMvc.perform(
put("/api/cars/{id}", VALID_LARGE_ID_1234567)
.content(jsonRequest)
.contentType(MediaType.APPLICATION_JSON)
)
.andExpect(status().isOk())
.andReturn();

CarResponseDto actual = objectMapper
.readValue(mvcResult.getResponse().getContentAsString(), CarResponseDto.class);

assertThat(actual).isEqualTo(expected);
}
}
Loading