Reputation: 1112
I want to test only the persistence layer using @DataJpaTest, and I have two datasource configurations, one in src/main and the other is src/test, and I am using @primary on test datasource to get picked up only, but main datasource get picked up also.
src/main configuration
@Configuration
@EnableTransactionManagement
@EnableJpaRepositories(basePackages = "com.****.repository",
entityManagerFactoryRef = "platformEntityManagerFactory",
transactionManagerRef = "platformTransactionManager"
)
@Import(CommonPersistenceConfig.class)
public class PlatformPersistenceConfig {
@Value("classpath:application.yml")
private Resource resource;
@Bean
@Qualifier("platformTransactionManager")
public PlatformTransactionManager platformTransactionManager(@Qualifier("platformEntityManagerFactory") EntityManagerFactory entityManagerFactory) {
// code...
}
@Bean
public LocalContainerEntityManagerFactoryBean platformEntityManagerFactory(DataSource dataSource,
HibernateProperties hibernateProperties) {
// code...
}
@Bean
public DataSource getDataSource() throws IOException, NoSuchPaddingException, NoSuchAlgorithmException, InvalidKeyException, BadPaddingException, IllegalBlockSizeException {
// code...
}
}
src/test configuration
@Configuration
@Import({CommonPersistenceConfig.class, DbPropertyConfig.class})
public class DbTestSetupConfig {
@Autowired
private TestDatasourceProperties dbProperties;
@Primary
@Bean(destroyMethod = "close")
public DataSource getDataSource() throws Exception {
// code...
}
@PostConstruct
public void dbSetup() throws Exception {
// code...
}
}
my test
@DataJpaTest
@AutoConfigureTestDatabase(replace = AutoConfigureTestDatabase.Replace.NONE)
public class StripeCardRepositoryTest {
@Autowired
StripeCardRepository stripeCardRepository;
@Test
public void test() {
}
}
Upvotes: 0
Views: 646
Reputation: 18939
The point of @AutoConfigureTestDatabase is to replace an existing datasource defined in src/main/.. with a datasource defined in src/test. But to do so you must inform it what strategy it must use. You have chosen AutoConfigureTestDatabase.Replace.NONE
therefore it does not replace the main datasource with the one that you need.
Try to switch to AutoConfigureTestDatabase.Replace.ANY
and it will correctly replace it with the one defined in test.
Also probably you show this in the documentation
In the case of multiple DataSource beans, only the @Primary DataSource is considered.
This applies in the case that you have multiple datasources in project defined. It means that it would replace only the primary datasource with the strategy defined. It does not mean that it would pick only the primary and ignore the others.
Upvotes: 1