New unit test format

This commit is contained in:
Nick
2019-08-30 21:11:18 +01:00
parent db85c8f275
commit 6cd385e4c0
19972 changed files with 1626600 additions and 0 deletions
@@ -0,0 +1,68 @@
package org.baeldung.examples.r2dbc;
import java.math.BigDecimal;
public class Account {
private Long id;
private String iban;
private BigDecimal balance;
public Account() {}
public Account(Long id, String iban, BigDecimal balance) {
this.id = id;
this.iban = iban;
this.balance = balance;
}
public Account(Long id, String iban, Double balance) {
this.id = id;
this.iban = iban;
this.balance = new BigDecimal(balance);
}
/**
* @return the id
*/
public Long getId() {
return id;
}
/**
* @param id the id to set
*/
public void setId(Long id) {
this.id = id;
}
/**
* @return the iban
*/
public String getIban() {
return iban;
}
/**
* @param iban the iban to set
*/
public void setIban(String iban) {
this.iban = iban;
}
/**
* @return the balance
*/
public BigDecimal getBalance() {
return balance;
}
/**
* @param balance the balance to set
*/
public void setBalance(BigDecimal balance) {
this.balance = balance;
}
}
@@ -0,0 +1,56 @@
/**
*
*/
package org.baeldung.examples.r2dbc;
import java.math.BigDecimal;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
/**
* @author Philippe
*
*/
@RestController
public class AccountResource {
private final ReactiveAccountDao accountDao;
public AccountResource(ReactiveAccountDao accountDao) {
this.accountDao = accountDao;
}
@GetMapping("/accounts/{id}")
public Mono<ResponseEntity<Account>> getAccount(@PathVariable("id") Long id) {
return accountDao.findById(id)
.map(acc -> new ResponseEntity<>(acc, HttpStatus.OK))
.switchIfEmpty(Mono.just(new ResponseEntity<>(null, HttpStatus.NOT_FOUND)));
}
@GetMapping("/accounts")
public Flux<Account> getAllAccounts() {
return accountDao.findAll();
}
@PostMapping("/accounts")
public Mono<ResponseEntity<Account>> postAccount(@RequestBody Account account) {
return accountDao.createAccount(account)
.map(acc -> new ResponseEntity<>(acc, HttpStatus.CREATED))
.log();
}
}
@@ -0,0 +1,65 @@
package org.baeldung.examples.r2dbc;
import org.springframework.boot.CommandLineRunner;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.util.StringUtils;
import io.netty.util.internal.StringUtil;
import io.r2dbc.spi.ConnectionFactories;
import io.r2dbc.spi.ConnectionFactory;
import io.r2dbc.spi.ConnectionFactoryOptions;
import io.r2dbc.spi.ConnectionFactoryOptions.Builder;
import io.r2dbc.spi.Option;
import reactor.core.publisher.Flux;
import static io.r2dbc.spi.ConnectionFactoryOptions.*;
@Configuration
public class DatasourceConfig {
@Bean
public ConnectionFactory connectionFactory(R2DBCConfigurationProperties properties) {
ConnectionFactoryOptions baseOptions = ConnectionFactoryOptions.parse(properties.getUrl());
Builder ob = ConnectionFactoryOptions.builder().from(baseOptions);
if ( !StringUtil.isNullOrEmpty(properties.getUser())) {
ob = ob.option(USER, properties.getUser());
}
if ( !StringUtil.isNullOrEmpty(properties.getPassword())) {
ob = ob.option(PASSWORD, properties.getPassword());
}
ConnectionFactory cf = ConnectionFactories.get(ob.build());
return cf;
}
@Bean
public CommandLineRunner initDatabase(ConnectionFactory cf) {
return (args) ->
Flux.from(cf.create())
.flatMap(c ->
Flux.from(c.createBatch()
.add("drop table if exists Account")
.add("create table Account(" +
"id IDENTITY(1,1)," +
"iban varchar(80) not null," +
"balance DECIMAL(18,2) not null)")
.add("insert into Account(iban,balance)" +
"values('BR430120980198201982',100.00)")
.add("insert into Account(iban,balance)" +
"values('BR430120998729871000',250.00)")
.execute())
.doFinally((st) -> c.close())
)
.log()
.blockLast();
}
}
@@ -0,0 +1,58 @@
package org.baeldung.examples.r2dbc;
import javax.validation.constraints.NotEmpty;
import org.springframework.boot.context.properties.ConfigurationProperties;
@ConfigurationProperties(prefix = "r2dbc")
public class R2DBCConfigurationProperties {
@NotEmpty
private String url;
private String user;
private String password;
/**
* @return the url
*/
public String getUrl() {
return url;
}
/**
* @param url the url to set
*/
public void setUrl(String url) {
this.url = url;
}
/**
* @return the user
*/
public String getUser() {
return user;
}
/**
* @param user the user to set
*/
public void setUser(String user) {
this.user = user;
}
/**
* @return the password
*/
public String getPassword() {
return password;
}
/**
* @param password the password to set
*/
public void setPassword(String password) {
this.password = password;
}
}
@@ -0,0 +1,17 @@
package org.baeldung.examples.r2dbc;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
@SpringBootApplication
@EnableConfigurationProperties(R2DBCConfigurationProperties.class)
public class R2dbcExampleApplication {
public static void main(String[] args) {
SpringApplication.run(R2dbcExampleApplication.class, args);
}
}
@@ -0,0 +1,76 @@
package org.baeldung.examples.r2dbc;
import java.math.BigDecimal;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;
import io.r2dbc.spi.Connection;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Flux;
import reactor.core.publisher.Mono;
@Component
public class ReactiveAccountDao {
private ConnectionFactory connectionFactory;
public ReactiveAccountDao(ConnectionFactory connectionFactory) {
this.connectionFactory = connectionFactory;
}
public Mono<Account> findById(long id) {
return Mono.from(connectionFactory.create())
.flatMap(c -> Mono.from(c.createStatement("select id,iban,balance from Account where id = $1")
.bind("$1", id)
.execute())
.doFinally((st) -> close(c)))
.map(result -> result.map((row, meta) ->
new Account(row.get("id", Long.class),
row.get("iban", String.class),
row.get("balance", BigDecimal.class))))
.flatMap( p -> Mono.from(p));
}
public Flux<Account> findAll() {
return Mono.from(connectionFactory.create())
.flatMap((c) -> Mono.from(c.createStatement("select id,iban,balance from Account")
.execute())
.doFinally((st) -> close(c)))
.flatMapMany(result -> Flux.from(result.map((row, meta) -> {
Account acc = new Account();
acc.setId(row.get("id", Long.class));
acc.setIban(row.get("iban", String.class));
acc.setBalance(row.get("balance", BigDecimal.class));
return acc;
})));
}
public Mono<Account> createAccount(Account account) {
return Mono.from(connectionFactory.create())
.flatMap(c -> Mono.from(c.beginTransaction())
.then(Mono.from(c.createStatement("insert into Account(iban,balance) values($1,$2)")
.bind("$1", account.getIban())
.bind("$2", account.getBalance())
.returnGeneratedValues("id")
.execute()))
.map(result -> result.map((row, meta) ->
new Account(row.get("id", Long.class),
account.getIban(),
account.getBalance())))
.flatMap(pub -> Mono.from(pub))
.delayUntil(r -> c.commitTransaction())
.doFinally((st) -> c.close()));
}
private <T> Mono<T> close(Connection connection) {
return Mono.from(connection.close())
.then(Mono.empty());
}
}
@@ -0,0 +1,5 @@
{"properties": [{
"name": "r2dbc",
"type": "org.baeldung.examples.r2dbc.R2DBCConfigurationProperties",
"description": "R2DBC Connection properties"
}]}
@@ -0,0 +1,13 @@
spring:
application:
name: r2dbc-test
# R2DBC URL
r2dbc:
url: r2dbc:h2:mem://./testdb
@@ -0,0 +1,102 @@
package org.baeldung.examples.r2dbc;
import static org.hamcrest.CoreMatchers.*;
import static org.junit.Assert.*;
import java.util.List;
import org.hamcrest.core.IsNull;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.test.web.reactive.server.WebTestClient;
import io.r2dbc.spi.ConnectionFactory;
import reactor.core.publisher.Flux;
@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class R2dbcExampleApplicationTests {
@Autowired
private WebTestClient webTestClient;
@Autowired
ConnectionFactory cf;
@Before
public void initDatabase() {
Flux.from(cf.create())
.flatMap(c ->
c.createBatch()
.add("drop table if exists Account")
.add("create table Account(id IDENTITY(1,1), iban varchar(80) not null, balance DECIMAL(18,2) not null)")
.add("insert into Account(iban,balance) values ( 'BR430120980198201982', 100.00 ) ")
.add("insert into Account(iban,balance) values ( 'BR430120998729871000', 250.00 ) ")
.execute()
)
.log()
.blockLast();
}
@Test
public void givenExistingAccountId_whenGetAccount_thenReturnExistingAccountInfo() {
webTestClient
.get()
.uri("/accounts/1")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(Account.class)
.value((acc) -> {
assertThat(acc.getId(),is(1l));
});
}
@Test
public void givenDatabaseHasSomeAccounts_whenGetAccount_thenReturnExistingAccounts() {
webTestClient
.get()
.uri("/accounts")
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.isOk()
.expectBody(List.class)
.value((accounts) -> {
assertThat(accounts.size(),not(is(0)));
});
}
@Test
public void givenNewAccountData_whenPostAccount_thenReturnNewAccountInfo() {
webTestClient
.post()
.uri("/accounts")
.syncBody(new Account(null,"BR4303010298012098", 151.00 ))
.accept(MediaType.APPLICATION_JSON)
.exchange()
.expectStatus()
.is2xxSuccessful()
.expectBody(Account.class)
.value((acc) -> {
assertThat(acc.getId(),is(notNullValue()));
});
}
}
@@ -0,0 +1,6 @@
# R2DBC Test configuration
r2dbc:
url: r2dbc:h2:mem://./testdb