что-то есть, но не правильно работает (возможно я слишком много придумал) сделал сумму в строке заказа, сделал добавление строк заказа в заказ, но это не правильно работает, по сути я создаю новою строку в самом заказе

This commit is contained in:
Алексей Крюков 2024-04-09 23:57:40 +04:00
parent 176d2bbbb4
commit 80fee84170
36 changed files with 196 additions and 89 deletions

Binary file not shown.

Binary file not shown.

View File

@ -19,6 +19,9 @@ dependencies {
implementation 'org.springframework.boot:spring-boot-starter-web' implementation 'org.springframework.boot:spring-boot-starter-web'
implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0' implementation 'org.springdoc:springdoc-openapi-starter-webmvc-ui:2.3.0'
implementation 'org.modelmapper:modelmapper:3.2.0' implementation 'org.modelmapper:modelmapper:3.2.0'
implementation 'javax.persistence:javax.persistence-api:2.2'
implementation 'javax.persistence:javax.persistence-api:2.2'
testImplementation 'org.springframework.boot:spring-boot-starter-test' testImplementation 'org.springframework.boot:spring-boot-starter-test'
} }

View File

@ -1,5 +1,7 @@
package com.example.demo; package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -8,6 +10,7 @@ import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.SpringApplication; import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.boot.autoconfigure.SpringBootApplication;
import com.example.demo.order_lines.model.OrderLineEntity;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService; import com.example.demo.orders.service.OrderService;
import com.example.demo.products.model.ProductEntity; import com.example.demo.products.model.ProductEntity;
@ -61,8 +64,11 @@ public class DemoApplication implements CommandLineRunner {
userService.create(new UserEntity(null, "Oleg", "Zyngin", "@mail.ru", "password")); userService.create(new UserEntity(null, "Oleg", "Zyngin", "@mail.ru", "password"));
log.info("Create default orders values"); log.info("Create default orders values");
@SuppressWarnings({ "rawtypes", "unchecked" })
List<OrderLineEntity> lines = new ArrayList();
lines.add(new OrderLineEntity(null, null, 3, null));
final var user1 = userService.create(new UserEntity(null, "Alex", "Kryukov", "akryu@mail.ru", "password")); final var user1 = userService.create(new UserEntity(null, "Alex", "Kryukov", "akryu@mail.ru", "password"));
orderService.create(new OrderEntity(null, user1, "31-03-2024")); orderService.create(new OrderEntity(null, user1, lines));
} }
} }
} }

View File

@ -15,8 +15,6 @@ import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants; import com.example.demo.core.configuration.Constants;
import com.example.demo.order_lines.model.OrderLineEntity; import com.example.demo.order_lines.model.OrderLineEntity;
import com.example.demo.order_lines.service.OrderLineService; import com.example.demo.order_lines.service.OrderLineService;
import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService;
import com.example.demo.products.model.ProductEntity; import com.example.demo.products.model.ProductEntity;
import com.example.demo.products.service.ProductService; import com.example.demo.products.service.ProductService;
@ -25,14 +23,12 @@ import jakarta.validation.Valid;
@RestController @RestController
@RequestMapping(Constants.API_URL + "/orderLine") @RequestMapping(Constants.API_URL + "/orderLine")
public class OrderLineController { public class OrderLineController {
private final OrderService orderService;
private final OrderLineService orderLineService; private final OrderLineService orderLineService;
private final ProductService productService; private final ProductService productService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
public OrderLineController(OrderLineService orderLineService, OrderService orderService, public OrderLineController(OrderLineService orderLineService,
ProductService productService, ModelMapper modelMapper) { ProductService productService, ModelMapper modelMapper) {
this.orderService = orderService;
this.orderLineService = orderLineService; this.orderLineService = orderLineService;
this.productService = productService; this.productService = productService;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
@ -44,15 +40,12 @@ public class OrderLineController {
private OrderLineEntity toEntity(OrderLineDto dto) { private OrderLineEntity toEntity(OrderLineDto dto) {
// Получаем заказ и товар из соответствующих сервисов по их идентификаторам из // Получаем заказ и товар из соответствующих сервисов по их идентификаторам из
// OrderLineDto
OrderEntity order = orderService.get(dto.getOrderId());
ProductEntity product = productService.get(dto.getProductId()); ProductEntity product = productService.get(dto.getProductId());
// Создаем новый экземпляр OrderLineEntity с помощью модельного маппера // Создаем новый экземпляр OrderLineEntity с помощью модельного маппера
OrderLineEntity entity = modelMapper.map(dto, OrderLineEntity.class); OrderLineEntity entity = modelMapper.map(dto, OrderLineEntity.class);
// Устанавливаем полученные заказ и товар в OrderLineEntity // Устанавливаем полученные заказ и товар в OrderLineEntity
entity.setOrder(order);
entity.setProduct(product); entity.setProduct(product);
return entity; return entity;
@ -70,7 +63,26 @@ public class OrderLineController {
@PostMapping @PostMapping
public OrderLineDto create(@RequestBody @Valid OrderLineDto dto) { public OrderLineDto create(@RequestBody @Valid OrderLineDto dto) {
return toDto(orderLineService.create(toEntity(dto))); // Получаем информацию о продукте по его ID
ProductEntity product = productService.get(dto.getProductId());
// Рассчитываем общую сумму строки заказа
double totalPrice = product.getPrice() * dto.getCount();
// Создаем новую сущность строки заказа
OrderLineEntity orderLineEntity = toEntity(dto);
// Устанавливаем общую сумму в сущность строки заказа
orderLineEntity.setTotalPrice(totalPrice);
// Создаем строку заказа
OrderLineEntity createdOrderLine = orderLineService.create(orderLineEntity);
// Преобразуем созданную строку заказа в DTO
OrderLineDto createdOrderLineDto = toDto(createdOrderLine);
// Возвращаем созданную строку заказа в виде DTO с заполненным полем totalPrice
return createdOrderLineDto;
} }
@PutMapping("/{id}") @PutMapping("/{id}")

View File

@ -7,17 +7,24 @@ import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
public class OrderLineDto { public class OrderLineDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1) @Min(1)
private Long orderId;
@NotNull
@Min(1)
private Long productId; private Long productId;
@NotBlank @NotBlank
private Integer count; private Integer count;
@JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Double totalPriceLine;
public Double getTotalPriceLine() {
return totalPriceLine;
}
public void setTotalPriceLine(Double totalPriceLine) {
this.totalPriceLine = totalPriceLine;
}
public Long getId() { public Long getId() {
return id; return id;
} }
@ -26,14 +33,6 @@ public class OrderLineDto {
this.id = id; this.id = id;
} }
public Long getOrderId() {
return orderId;
}
public void setOrderId(Long orderId) {
this.orderId = orderId;
}
public Integer getCount() { public Integer getCount() {
return count; return count;
} }

View File

@ -2,25 +2,33 @@ package com.example.demo.order_lines.model;
import java.util.Objects; import java.util.Objects;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import com.example.demo.core.model.BaseEntity; import com.example.demo.core.model.BaseEntity;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.products.model.ProductEntity; import com.example.demo.products.model.ProductEntity;
import com.fasterxml.jackson.annotation.JsonBackReference;
public class OrderLineEntity extends BaseEntity { public class OrderLineEntity extends BaseEntity {
private OrderEntity order;
private Integer count; private Integer count;
private ProductEntity product; private ProductEntity product;
private Double totalPrice;
@ManyToOne
@JoinColumn(name = "order_id")
@JsonBackReference // Это свойство не управляется родительским объектом
private OrderEntity order;
public OrderLineEntity() { public OrderLineEntity() {
} }
public OrderLineEntity(Long id, OrderEntity order, ProductEntity product, Integer count) { public OrderLineEntity(Long id, ProductEntity product, Integer count, Double totalPrice) {
super(id); super(id);
this.order = order;
this.count = count;
this.product = product; this.product = product;
this.count = count;
this.totalPrice = totalPrice;
} }
public ProductEntity getProduct() { public ProductEntity getProduct() {
@ -31,14 +39,6 @@ public class OrderLineEntity extends BaseEntity {
this.product = product; this.product = product;
} }
public OrderEntity getOrder() {
return order;
}
public void setOrder(OrderEntity order) {
this.order = order;
}
public Integer getCount() { public Integer getCount() {
return count; return count;
} }
@ -47,9 +47,17 @@ public class OrderLineEntity extends BaseEntity {
this.count = count; this.count = count;
} }
public Double getTotalPrice() {
return totalPrice;
}
public void setTotalPrice(Double totalPrice) {
this.totalPrice = totalPrice;
}
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, order, product, count); return Objects.hash(id, product, count);
} }
@SuppressWarnings("unlikely-arg-order-product") @SuppressWarnings("unlikely-arg-order-product")
@ -61,7 +69,6 @@ public class OrderLineEntity extends BaseEntity {
return false; return false;
final OrderLineEntity other = (OrderLineEntity) obj; final OrderLineEntity other = (OrderLineEntity) obj;
return Objects.equals(other.getId(), id) return Objects.equals(other.getId(), id)
&& Objects.equals(other.getOrder(), order)
&& Objects.equals(other.getProduct(), product) && Objects.equals(other.getProduct(), product)
&& Objects.equals(other.getCount(), count); && Objects.equals(other.getCount(), count);
} }

View File

@ -22,9 +22,7 @@ public class OrderLineService {
if (Objects.equals(orderLineId, 0L)) { if (Objects.equals(orderLineId, 0L)) {
return repository.getAll(); return repository.getAll();
} }
return repository.getAll().stream() return repository.getAll();
.filter(orderLine -> orderLine.getOrder().getId().equals(orderLineId))
.toList();
} }
public OrderLineEntity get(Long id) { public OrderLineEntity get(Long id) {
@ -38,7 +36,6 @@ public class OrderLineService {
public OrderLineEntity update(Long id, OrderLineEntity entity) { public OrderLineEntity update(Long id, OrderLineEntity entity) {
final OrderLineEntity existsEntity = get(id); final OrderLineEntity existsEntity = get(id);
existsEntity.setOrder(entity.getOrder());
existsEntity.setProduct(entity.getProduct()); existsEntity.setProduct(entity.getProduct());
existsEntity.setCount(entity.getCount()); existsEntity.setCount(entity.getCount());
return repository.update(existsEntity); return repository.update(existsEntity);

View File

@ -1,7 +1,8 @@
package com.example.demo.orders.api; package com.example.demo.orders.api;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import org.modelmapper.ModelMapper; import org.modelmapper.ModelMapper;
import org.springframework.web.bind.annotation.DeleteMapping; import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.GetMapping;
@ -13,10 +14,12 @@ import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController; import org.springframework.web.bind.annotation.RestController;
import com.example.demo.core.configuration.Constants; import com.example.demo.core.configuration.Constants;
import com.example.demo.order_lines.api.OrderLineDto;
import com.example.demo.order_lines.model.OrderLineEntity;
import com.example.demo.order_lines.service.OrderLineService;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService; import com.example.demo.orders.service.OrderService;
import com.example.demo.users.service.UserService; import com.example.demo.users.service.UserService;
import jakarta.validation.Valid; import jakarta.validation.Valid;
@RestController @RestController
@ -25,26 +28,54 @@ public class OrderController {
private final OrderService orderService; private final OrderService orderService;
private final UserService userService; private final UserService userService;
private final ModelMapper modelMapper; private final ModelMapper modelMapper;
private final OrderLineService orderLineService;
public OrderController(OrderService orderService, UserService userService, ModelMapper modelMapper) { public OrderController(OrderService orderService, UserService userService, ModelMapper modelMapper,
OrderLineService orderLineService) {
this.orderService = orderService; this.orderService = orderService;
this.userService = userService; this.userService = userService;
this.modelMapper = modelMapper; this.modelMapper = modelMapper;
this.orderLineService = orderLineService;
} }
private OrderDto toDto(OrderEntity entity) { private OrderDto toDto(OrderEntity entity) {
return modelMapper.map(entity, OrderDto.class); var dto = new OrderDto();
dto.setId(entity.getId());
dto.setUserId(entity.getUser().getId());
// Преобразование каждой сущности OrderLineEntity в OrderLineDto и добавление их
// в список lines
for (OrderLineEntity orderLineEntity : entity.getLines()) {
OrderLineDto orderLineDto = new OrderLineDto();
orderLineDto.setId(orderLineEntity.getId());
orderLineDto.setProductId(orderLineEntity.getProduct().getId());
orderLineDto.setCount(orderLineEntity.getCount());
orderLineDto.setTotalPriceLine(orderLineEntity.getTotalPrice());
dto.addOrderLine(orderLineDto);
}
dto.setDate(new Date(System.currentTimeMillis()));
return dto;
} }
private OrderEntity toEntity(OrderDto dto) { public OrderEntity toEntity(OrderDto dto) {
final OrderEntity entity = modelMapper.map(dto, OrderEntity.class); final OrderEntity entity = modelMapper.map(dto, OrderEntity.class);
entity.setUser(userService.get(dto.getUserId())); if (dto.getUserId() != null) {
entity.setUser(userService.get(dto.getUserId()));
}
// устанавливаем связь между заказом и строками заказа
entity.getLines().clear();
for (OrderLineDto lineDto : dto.getLines()) {
OrderLineEntity orderLineEntity = modelMapper.map(lineDto, OrderLineEntity.class);
entity.addOrderLine(orderLineEntity);
}
return entity; return entity;
} }
@GetMapping @GetMapping
public List<OrderDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Long userId) { public List<OrderDto> getAll(@RequestParam(name = "userId", defaultValue = "0") Long userId,
return orderService.getAll(userId).stream().map(this::toDto).toList(); @RequestParam(name = "lines", defaultValue = "") List<Long> lines) {
return orderService.getAll(userId, lines).stream().map(this::toDto).toList();
} }
@GetMapping("/{id}") @GetMapping("/{id}")
@ -54,7 +85,8 @@ public class OrderController {
@PostMapping @PostMapping
public OrderDto create(@RequestBody @Valid OrderDto dto) { public OrderDto create(@RequestBody @Valid OrderDto dto) {
return toDto(orderService.create(toEntity(dto))); OrderEntity orderEntity = toEntity(dto);
return toDto(orderService.create(orderEntity));
} }
@PutMapping("/{id}") @PutMapping("/{id}")

View File

@ -1,20 +1,26 @@
package com.example.demo.orders.api; package com.example.demo.orders.api;
import java.sql.Date;
import java.util.ArrayList;
import java.util.List;
import com.example.demo.order_lines.api.OrderLineDto;
import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonProperty;
import jakarta.validation.constraints.Min; import jakarta.validation.constraints.Min;
import jakarta.validation.constraints.NotBlank;
import jakarta.validation.constraints.NotNull; import jakarta.validation.constraints.NotNull;
public class OrderDto { public class OrderDto {
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Long id; private Long id;
@NotNull @NotNull
@Min(1) @Min(1)
private Long userId; private Long userId;
@NotBlank
private String date;
@JsonProperty(access = JsonProperty.Access.READ_ONLY) @JsonProperty(access = JsonProperty.Access.READ_ONLY)
private Date date = getDate();
@NotNull
private final List<OrderLineDto> lines = new ArrayList<>();
public Long getId() { public Long getId() {
return id; return id;
} }
@ -31,11 +37,21 @@ public class OrderDto {
this.userId = userId; this.userId = userId;
} }
public String getDate() { public void setDate(Date date) {
return date;
}
public void setDate(String date) {
this.date = date; this.date = date;
} }
public List<OrderLineDto> getLines() {
return lines;
}
// метод для добавленя строк заказа
public void addOrderLine(OrderLineDto orderLine) {
this.lines.add(orderLine);
}
@JsonProperty(access = JsonProperty.Access.READ_ONLY)
public Date getDate() {
return date;
}
} }

View File

@ -1,22 +1,28 @@
package com.example.demo.orders.model; package com.example.demo.orders.model;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects; import java.util.Objects;
import com.example.demo.core.model.BaseEntity; import com.example.demo.core.model.BaseEntity;
import com.example.demo.order_lines.model.OrderLineEntity;
import com.example.demo.users.model.UserEntity; import com.example.demo.users.model.UserEntity;
import com.fasterxml.jackson.annotation.JsonManagedReference;
public class OrderEntity extends BaseEntity { public class OrderEntity extends BaseEntity {
private UserEntity user; private UserEntity user;
private String date; @JsonManagedReference
private final List<OrderLineEntity> lines = new ArrayList<>();
public OrderEntity() { public OrderEntity() {
// Пустой конструктор super();
} }
public OrderEntity(Long id, UserEntity user, String date) { public OrderEntity(Long id, UserEntity user, List<OrderLineEntity> lines) {
super(id); super(id);
this.user = user; this.user = user;
this.date = date; this.lines.clear();
this.lines.addAll(lines);
} }
public UserEntity getUser() { public UserEntity getUser() {
@ -27,17 +33,17 @@ public class OrderEntity extends BaseEntity {
this.user = user; this.user = user;
} }
public String getDate() { public List<OrderLineEntity> getLines() {
return date; return lines;
} }
public void setDate(String date) { public void setLines(OrderLineEntity line) {
this.date = date; this.lines.add(line);
} }
@Override @Override
public int hashCode() { public int hashCode() {
return Objects.hash(id, user, date); return Objects.hash(id, user, lines);
} }
@SuppressWarnings("unlikely-arg-user") @SuppressWarnings("unlikely-arg-user")
@ -50,6 +56,11 @@ public class OrderEntity extends BaseEntity {
final OrderEntity other = (OrderEntity) obj; final OrderEntity other = (OrderEntity) obj;
return Objects.equals(other.getId(), id) return Objects.equals(other.getId(), id)
&& Objects.equals(other.getUser(), user) && Objects.equals(other.getUser(), user)
&& Objects.equals(other.getDate(), date); && Objects.equals(other.getLines(), lines);
}
// метод добавления строк заказа в заказ
public void addOrderLine(OrderLineEntity orderLine) {
this.lines.add(orderLine);
} }
} }

View File

@ -1,5 +1,6 @@
package com.example.demo.orders.service; package com.example.demo.orders.service;
import java.util.ArrayList;
import java.util.List; import java.util.List;
import java.util.Objects; import java.util.Objects;
import java.util.Optional; import java.util.Optional;
@ -7,24 +8,40 @@ import java.util.Optional;
import org.springframework.stereotype.Service; import org.springframework.stereotype.Service;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.order_lines.service.OrderLineService;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.repository.OrderRepository; import com.example.demo.orders.repository.OrderRepository;
@Service @Service
public class OrderService { public class OrderService {
private final OrderRepository repository; private final OrderRepository repository;
private final OrderLineService orderLineService;
public OrderService(OrderRepository repository) { public OrderService(OrderRepository repository, OrderLineService orderLineService) {
this.repository = repository; this.repository = repository;
this.orderLineService = orderLineService;
} }
public List<OrderEntity> getAll(Long userId) { public List<OrderEntity> getAll(Long userId, List<Long> lines) {
if (Objects.equals(userId, 0L)) {
return repository.getAll(); var linesEnt = new ArrayList<>();
for (var lineid : lines) {
linesEnt.add(orderLineService.get(lineid));
} }
return repository.getAll().stream()
.filter(order -> order.getUser().getId().equals(userId)) if (!Objects.equals(userId, 0L) && !Objects.equals(linesEnt.size(), 0)) {
.toList(); return repository.getAll().stream()
.filter(line -> line.getUser().getId().equals(
userId) && line.getLines().containsAll(linesEnt))
.toList();
}
if (Objects.equals(userId, 0L) && !Objects.equals(linesEnt.size(), 0)) {
return repository.getAll().stream().filter(line -> line.getLines().containsAll(linesEnt)).toList();
}
if (!Objects.equals(userId, 0L) && Objects.equals(linesEnt.size(), 0)) {
return repository.getAll().stream().filter(line -> line.getUser().getId().equals(userId)).toList();
}
return repository.getAll();
} }
public OrderEntity get(Long id) { public OrderEntity get(Long id) {
@ -37,10 +54,14 @@ public class OrderService {
} }
public OrderEntity update(Long id, OrderEntity entity) { public OrderEntity update(Long id, OrderEntity entity) {
final OrderEntity existsEntity = get(id); final OrderEntity existEntity = get(id);
existsEntity.setUser(entity.getUser()); existEntity.setUser(entity.getUser());
existsEntity.setDate(entity.getDate()); existEntity.getLines().clear(); // Очищаем существующие строки заказа
return repository.update(existsEntity); var lines = entity.getLines();
for (var line : lines) {
existEntity.setLines(line);
}
return repository.update(existEntity);
} }
public OrderEntity delete(Long id) { public OrderEntity delete(Long id) {

View File

@ -26,7 +26,7 @@ class OrderLineServiceTests {
@Order(1) @Order(1)
void createTest() { void createTest() {
// Создаем тестовую сущность OrderLineEntity // Создаем тестовую сущность OrderLineEntity
OrderLineEntity testOrderLine = new OrderLineEntity(null, null, null, 5); OrderLineEntity testOrderLine = new OrderLineEntity(null, null, 5, null);
// Вызываем метод create() и сохраняем созданную сущность // Вызываем метод create() и сохраняем созданную сущность
OrderLineEntity createdOrderLine = orderLineService.create(testOrderLine); OrderLineEntity createdOrderLine = orderLineService.create(testOrderLine);
// Проверяем, что метод create() вернул не null // Проверяем, что метод create() вернул не null

View File

@ -1,5 +1,8 @@
package com.example.demo; package com.example.demo;
import java.util.ArrayList;
import java.util.List;
import org.junit.jupiter.api.Assertions; import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.MethodOrderer; import org.junit.jupiter.api.MethodOrderer;
import org.junit.jupiter.api.Order; import org.junit.jupiter.api.Order;
@ -8,6 +11,7 @@ import org.junit.jupiter.api.TestMethodOrder;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest; import org.springframework.boot.test.context.SpringBootTest;
import com.example.demo.core.error.NotFoundException; import com.example.demo.core.error.NotFoundException;
import com.example.demo.order_lines.model.OrderLineEntity;
import com.example.demo.orders.model.OrderEntity; import com.example.demo.orders.model.OrderEntity;
import com.example.demo.orders.service.OrderService; import com.example.demo.orders.service.OrderService;
@ -25,16 +29,21 @@ class OrderServiceTests {
@Test @Test
@Order(1) @Order(1)
void createTest() { void createTest() {
orderService.create(new OrderEntity(null, null, null));
@SuppressWarnings({ "rawtypes", "unchecked" })
List<OrderLineEntity> lines = new ArrayList();
lines.add(new OrderLineEntity(null, null, 4, null));
lines.add(new OrderLineEntity(null, null, 5, null));
lines.add(new OrderLineEntity(null, null, 6, null));
lines.add(new OrderLineEntity(null, null, 7, null));
// Создаем тестовую сущность OrderEntity // Создаем тестовую сущность OrderEntity
OrderEntity testOrder = new OrderEntity(null, null, "2024-04-01"); OrderEntity testOrder = new OrderEntity(null, null, lines);
// Вызываем метод create() и сохраняем созданную сущность // Вызываем метод create() и сохраняем созданную сущность
OrderEntity createdOrder = orderService.create(testOrder); OrderEntity createdOrder = orderService.create(testOrder);
// Проверяем, что метод create() вернул не null // Проверяем, что метод create() вернул не null
Assertions.assertNotNull(createdOrder); Assertions.assertNotNull(createdOrder);
// Проверяем, что созданная сущность имеет назначенный ID // Проверяем, что созданная сущность имеет назначенный ID
Assertions.assertNotNull(createdOrder.getId()); Assertions.assertNotNull(createdOrder.getId());
// Проверяем, что созданная сущность соответствует той, которую мы передали
Assertions.assertEquals(testOrder.getDate(), createdOrder.getDate());
} }
@Test @Test
@ -42,16 +51,10 @@ class OrderServiceTests {
void updateTest() { void updateTest() {
// Получаем сущность OrderEntity для обновления // Получаем сущность OrderEntity для обновления
OrderEntity existingOrder = orderService.get(1L); OrderEntity existingOrder = orderService.get(1L);
// Создаем новую дату для обновления
String newDate = "2024-04-02";
// Устанавливаем новую дату в сущность OrderEntity
existingOrder.setDate(newDate);
// Вызываем метод update() и сохраняем обновленную сущность // Вызываем метод update() и сохраняем обновленную сущность
OrderEntity updatedOrder = orderService.update(1L, existingOrder); OrderEntity updatedOrder = orderService.update(1L, existingOrder);
// Проверяем, что метод update() вернул не null // Проверяем, что метод update() вернул не null
Assertions.assertNotNull(updatedOrder); Assertions.assertNotNull(updatedOrder);
// Проверяем, что обновленная сущность имеет ту же дату, что и заданная
Assertions.assertEquals(newDate, updatedOrder.getDate());
} }
@Test @Test