Spring Framework
Importing
import org.springframework.transaction.annotation.Transactional;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.jdbc.JdbcTestUtils;
import guru.mikelue.foxglove.TableFacet;
import guru.mikelue.foxglove.annotation.GenData;
import guru.mikelue.foxglove.annotation.TableFacetsSource;
import guru.mikelue.foxglove.functional.TableFacetProvider;
import guru.mikelue.foxglove.jdbc.JdbcTableFacet;
import guru.mikelue.foxglove.springframework.EnableFoxglove;Following example using following context configuration of SpringFramework.
Context Configuration
@Configuration
class SampleTestConfig {
@Bean
ToyotaCarsProvider toyotaCars()
{
return new ToyotaCarsProvider();
}
@Bean @Scope("prototype")
TableFacet blueCars()
{
return JdbcTableFacet.builder("ap_car")
.numberOfRows(SpringFrameworkTest.RANDOM_ROWS)
.column("cr_color").fixed("blue")
.build();
}
@Bean
TableFacetProvider<TableFacet> yellowCars()
{
return () -> JdbcTableFacet.builder("ap_car")
.numberOfRows(SpringFrameworkTest.RANDOM_ROWS)
.column("cr_color").fixed("yellow")
.build();
}
@Bean @Scope("prototype")
TableFacet[] purpleCars()
{
return new TableFacet[] {
JdbcTableFacet.builder("ap_car")
.numberOfRows(SpringFrameworkTest.RANDOM_ROWS)
.column("cr_color").fixed("purple")
.build()
};
}
}@DataGenSource and @TableFacetsSource is still working if there are no such bean found in Spring’s context.
Note | @Nested tests of JUnit 5 are not supported with SpringFramework integration. |
Beans
Use bean definition as sources of TableFacets
@Test
@GenData(
// Uses the bean name of Spring Framework context
facetsNames = { "blueCars", "purpleCars", "yellowCars" }
)
void blueCarsTest(
@Autowired
JdbcTemplate jdbcTemplate
) {
assertThat(
JdbcTestUtils.countRowsInTableWhere(
jdbcTemplate,
"ap_car", "cr_color IN ('blue', 'purple', 'yellow')"
)
)
.isEqualTo(RANDOM_ROWS * 3);
}Use provider
class ToyotaCarsProvider implements TableFacetProvider<TableFacet> {
@Override
public TableFacet getOne()
{
return JdbcTableFacet.builder("ap_car")
.numberOfRows(SpringFrameworkTest.RANDOM_ROWS)
.column("cr_brand").fixed("Toyota")
.build();
}
}
@Test
@GenData(ToyotaCarsProvider.class)
void byProvider(
@Autowired
JdbcTemplate jdbcTemplate
) {
assertThat(
JdbcTestUtils.countRowsInTableWhere(
jdbcTemplate,
"ap_car", "cr_brand = 'Toyota'"
)
)
.isEqualTo(RANDOM_ROWS);
}Transaction
Not joining transactions
@AfterEach
void tearDownForYellowCars(
@Autowired
JdbcTemplate jdbcTemplate
) {
// You have to remove the data by yourself
JdbcTestUtils.deleteFromTableWhere(
jdbcTemplate,
"ap_car", "cr_color = 'yellow'"
);
}
@Test
@GenData(
facetsNames = { "yellowCars" }
)
@Transactional(propagation = Propagation.NOT_SUPPORTED)
void noRollback(
@Autowired
JdbcTemplate jdbcTemplate
) {
assertThat(
JdbcTestUtils.countRowsInTableWhere(
jdbcTemplate,
"ap_car", "cr_color = 'yellow'"
)
)
.isEqualTo(RANDOM_ROWS);
}