I am converting an old JDBC app into a spring-data-jpa app and I'm working on the first tests now. I kept seeing a security module instantiation error from spring-boot as it tried to bootstrap the security setup, even though @DataJpaTest
should theoretically be excluding it.
My problem with the security module probably stems from the pre-existing implementation which I inherited using PropertySourcesPlaceholderConfigurer
(via my PropertySpringConfig
import below)
Following the docs here:
http://docs.spring.io/spring-boot/docs/1.4.x/reference/htmlsingle/#test-auto-configuration
and your comments on @LiviaMorunianu's answer, I managed to work my way past every spring-boot exception and get JUnit to run with an auto-configured embedded DB.
My main/production spring-boot bootstrap class bootstraps everything including the stuff I want to exclude from my tests. So instead of using @DataJpaTest
, I copied much of what it is doing, using @Import
to bring in the centralized configurations that every test / live setup will use.
I also had issues because of the package structure I use, since initially I was running the test which was based in com.mycompany.repositories
and it didn't find the entities in com.mycompany.entities
.
Below are the relevant classes.
JUnit Test
@RunWith(SpringRunner.class)
@Transactional
@Import({TestConfiguration.class, LiveConfiguration.class})
public class ForecastRepositoryTests {
@Autowired
ForecastRepository repository;
Forecast forecast;
@Before
public void setUp() {
forecast = createDummyForecast(TEST_NAME, 12345L);
}
@Test
public void testFindSavedForecastById() {
forecast = repository.save(forecast);
assertThat(repository.findOne(forecast.getId()), is(forecast));
}
Live Configuration
@Configuration
@EnableJpaRepositories(basePackages = {"com.mycompany.repository"})
@EntityScan(basePackages = {"com.mycompany.entity"})
@Import({PropertySpringConfig.class})
public class LiveConfiguration {}
Test Configuration
@OverrideAutoConfiguration(enabled = false)
@ImportAutoConfiguration(value = {
CacheAutoConfiguration.class,
JpaRepositoriesAutoConfiguration.class,
DataSourceAutoConfiguration.class,
DataSourceTransactionManagerAutoConfiguration.class,
HibernateJpaAutoConfiguration.class,
TransactionAutoConfiguration.class,
TestDatabaseAutoConfiguration.class,
TestEntityManagerAutoConfiguration.class })
public class TestConfiguration {
// lots of bean definitions...
}
PropertySpringConfig
@Configuration
public class PropertySpringConfig {
@Bean
static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer()
throws IOException {
return new CorePropertySourcesPlaceholderConfigurer(
System.getProperties());
}
}