|
| 1 | +package com.example.kotlin; |
| 2 | + |
| 3 | +import com.example.onetomany.domain.Order; |
| 4 | +import com.example.onetomany.domain.Product; |
| 5 | +import com.example.onetomany.repository.OrderRepository; |
| 6 | +import com.example.onetomany.repository.ProductRepository; |
| 7 | +import org.junit.Test; |
| 8 | +import org.junit.runner.RunWith; |
| 9 | +import org.springframework.beans.factory.annotation.Autowired; |
| 10 | +import org.springframework.boot.test.autoconfigure.orm.jpa.DataJpaTest; |
| 11 | +import org.springframework.test.context.junit4.SpringRunner; |
| 12 | + |
| 13 | +import java.util.Arrays; |
| 14 | +import java.util.List; |
| 15 | + |
| 16 | +import static org.assertj.core.api.Assertions.assertThat; |
| 17 | + |
| 18 | +@RunWith(SpringRunner.class) |
| 19 | +@DataJpaTest |
| 20 | +public class OneToManyTests { |
| 21 | + |
| 22 | + @Autowired |
| 23 | + private OrderRepository orderRepository; |
| 24 | + |
| 25 | + @Autowired |
| 26 | + private ProductRepository productRepository; |
| 27 | + |
| 28 | + private static final String PRODUCT_NAME = "java"; |
| 29 | + |
| 30 | + @Test |
| 31 | + public void test_productFindByName() { |
| 32 | + // given |
| 33 | + insertBaseData(); |
| 34 | + |
| 35 | + // when |
| 36 | + Product product = productRepository.findByName(PRODUCT_NAME); |
| 37 | + |
| 38 | + // then |
| 39 | + assertThat(product.getName()).isEqualTo(PRODUCT_NAME); |
| 40 | + } |
| 41 | + |
| 42 | + private void insertBaseData() { |
| 43 | + Product javaProduct = new Product("java", "java content"); |
| 44 | + Product kotlinProduct = new Product("kotlin", "kotlin content"); |
| 45 | + Product scalaProduct = new Product("scala", "scala content"); |
| 46 | + |
| 47 | + productRepository.save(javaProduct); |
| 48 | + productRepository.save(kotlinProduct); |
| 49 | + productRepository.save(scalaProduct); |
| 50 | + |
| 51 | + javaProduct = productRepository.findByName(javaProduct.getName()); |
| 52 | + kotlinProduct = productRepository.findByName(kotlinProduct.getName()); |
| 53 | + scalaProduct = productRepository.findByName(scalaProduct.getName()); |
| 54 | + |
| 55 | + List<Order> javaOrders = Arrays.asList(new Order(3, "", javaProduct), new Order(3, "", javaProduct)); |
| 56 | + List<Order> kotlinOrders = Arrays.asList(new Order(2, "", kotlinProduct), new Order(2, "", kotlinProduct)); |
| 57 | + List<Order> scalaOrders = Arrays.asList(new Order(1, "", scalaProduct)); |
| 58 | + |
| 59 | + orderRepository.saveAll(javaOrders); |
| 60 | + orderRepository.saveAll(kotlinOrders); |
| 61 | + orderRepository.saveAll(scalaOrders); |
| 62 | + |
| 63 | + System.out.println("========================= Product ========================="); |
| 64 | + productRepository.findAll().forEach(System.out::println); |
| 65 | + System.out.println("========================== Order =========================="); |
| 66 | + orderRepository.findAll().forEach(System.out::println); |
| 67 | + } |
| 68 | +} |
0 commit comments