Created
May 16, 2020 09:24
-
-
Save j-tim/5ce1e228b67670efbbf11835c9af6d38 to your computer and use it in GitHub Desktop.
Spring Boot 2.3 - Spring Data R2dbc - @DataR2dbcTest test slice
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package com.example.r2dbc; | |
import io.r2dbc.spi.ConnectionFactory; | |
import org.junit.jupiter.api.Test; | |
import org.springframework.beans.factory.annotation.Autowired; | |
import org.springframework.boot.test.autoconfigure.data.r2dbc.DataR2dbcTest; | |
import org.springframework.core.io.DefaultResourceLoader; | |
import org.springframework.core.io.Resource; | |
import org.springframework.core.io.ResourceLoader; | |
import org.springframework.data.r2dbc.connectionfactory.init.ResourceDatabasePopulator; | |
import org.springframework.data.r2dbc.core.DatabaseClient; | |
import reactor.core.publisher.Flux; | |
import reactor.test.StepVerifier; | |
import static org.assertj.core.api.Assertions.assertThat; | |
@DataR2dbcTest | |
class CustomerRepositoryTest { | |
@Autowired | |
private DatabaseClient databaseClient; | |
@Autowired | |
private CustomerRepository customerRepository; | |
/** | |
* If you are using R2DBC, the regular DataSource auto-configuration backs off so | |
* no schema.sql and data.sql will be loaded automatically! | |
* | |
* Using Spring Data R2DBC you can initialize the database on startup yourself. | |
* In this case we initialize the database in this test. | |
* | |
* For more info check the docs: | |
* https://docs.spring.io/spring-boot/docs/current/reference/htmlsingle/#howto-initialize-a-database-using-r2dbc | |
*/ | |
@Autowired | |
public void initializeDatabase(ConnectionFactory connectionFactory) { | |
ResourceLoader resourceLoader = new DefaultResourceLoader(); | |
Resource[] scripts = new Resource[]{ | |
resourceLoader.getResource("classpath:schema.sql"), | |
resourceLoader.getResource("classpath:data.sql") | |
}; | |
new ResourceDatabasePopulator(scripts).execute(connectionFactory).block(); | |
} | |
@Test | |
public void testFindByLastName() { | |
Customer customer = new Customer("Tim", "van", "Baarsen"); | |
databaseClient.insert() | |
.into(Customer.class) | |
.using(customer) | |
.then() | |
.as(StepVerifier::create) | |
.verifyComplete(); | |
Flux<Customer> findByLastName = customerRepository.findByLastName(customer.getLastName()); | |
findByLastName.as(StepVerifier::create) | |
.assertNext(actual -> { | |
assertThat(actual.getFirstName()).isEqualTo("Tim"); | |
assertThat(actual.getMiddleName()).isEqualTo("van"); | |
assertThat(actual.getLastName()).isEqualTo("Baarsen"); | |
}) | |
.verifyComplete(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment