21 Ağustos 2022 Pazar

SpringBoot Test @Sql Anotasyonu - Entegrasyon Testlerinde Kullanılır

Giriş
Testcontainer kullanırken veri tabanını yaratmak gerekir. Seçenekler için açıklama şöyle
Create database schema
There are several ways to create database schema: 

1. Let Hibernate generate and execute DDL automatically;
2. Use DB versioning scripts (Flyway or Liquibase);
3. Create schema.sql DDL manually and run it using Spring Boot settings.
Daha sonra veri tabanını doldurmak gerekir. Seçenekler için açıklama şöyle
To fill the database with test data, there are three main options: 

1. Insert data in the test code;
2. Use @Sql annotation for tests;
3. Use data.sql file and run it using Spring Boot settings.
The first option is good if you have a very small test dataset, literally a couple of tables and a couple of records for each table. When the database grows, we need to update tons of code: copy common data, keep track of references etc.

The @Sql annotation is great to run SQL scripts to fill the database with test-specific data. For every test we can create small maintainable scripts, and we can see their names right above the test methods. That's convenient.

As for the data.sql file – we can use it together with schema.sql. It can be used to fill the database with common reference data like countries, cities, etc.
Örnek
Şöyle yaparız
import org.springframework.test.context.jdbc.Sql;

@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class OrderApiIntegrationTest {

  @LocalServerPort
  private int port;

  @Autowired
  private TestRestTemplate restTemplate;

  @Autowired
  private OrderRepository orderRepository;

  @Autowired
  private OrderService orderService;

  private static HttpHeaders headers;

  private final ObjectMapper objectMapper = new ObjectMapper();

  @BeforeAll
  public static void init() {
    headers = new HttpHeaders();
    headers.setContentType(MediaType.APPLICATION_JSON);
  }

  @Test
  @Sql(statements = "INSERT INTO orders(id, buyer, price, qty) VALUES (22, 'john', 24.0, 1)", 
    executionPhase = Sql.ExecutionPhase.BEFORE_TEST_METHOD)
  @Sql(statements = "DELETE FROM orders WHERE id='22'", 
    executionPhase = Sql.ExecutionPhase.AFTER_TEST_METHOD)
  public void testOrdersList() {
    HttpEntity<String> entity = new HttpEntity<>(null, headers);
    ResponseEntity<List<Order>> response = restTemplate.exchange(
      createURLWithPort(), HttpMethod.GET, entity, 
      new ParameterizedTypeReference<List<Order>>(){});

    List<Order> orderList = response.getBody();
    assert orderList != null;
    assertEquals(response.getStatusCodeValue(), 200);
    assertEquals(orderList.size(), orderService.getOrders().size());
    assertEquals(orderList.size(), orderRepository.findAll().size());
  }

  private String createURLWithPort() {
    return "http://localhost:" + port + "/api/orders";
  }
}



Hiç yorum yok:

Yorum Gönder