我有几个扩展JpaRepository
的存储库。现在,我想使用H2数据库的真实实例(不是内存中的-以便可以使用Web控制台检查数据库)来测试在单元测试中添加的自定义查询。
但是,自动连接单元中的存储库不起作用,我总是得到NoSuchBeanDefinitionException: No qualifying bean of type ... UserRepository available
。
存储库和单元测试的代码在下面列出。感谢您的帮助!
UserRepository
public interface UserRepository extends JpaRepository<User, Long> {}
UserRepositoryTests
@RunWith(SpringJUnit4ClassRunner.class)
@SpringBootTest
@ContextConfiguration(classes = TestConfiguration.class)
@Transactional
public class UserRepositoryTests {
@Autowired
private UserRepository userRepository;
@Test
@Commit
public void test() throws AESEncryptionException {
User user = new User().setFirstName("ABC").setLastName("XYZ");
user = userRepository.save(user);
assertNotNull(user.getId());
}
}
TestConfiguration
@Configuration
@EnableAutoConfiguration
@ComponentScan
@PropertySource("classpath:/application.properties")
public class TestConfiguration {}
application.properties
spring.datasource.url = jdbc:h2:file:./db/app-data
spring.datasource.driverClassName = org.h2.Driver
spring.jpa.database-platform = org.hibernate.dialect.H2Dialect
spring.jpa.hibernate.ddl-auto = update
spring.h2.console.settings.web-allow-others = true
编辑:
正如Mensur Qulami所建议的那样,删除@ContextConfiguration(classes = TestConfiguration.class)
可以解决问题,因为@SpringBootTest
已经涵盖了这一点。
答案 0 :(得分:1)
您可以结合使用 DataJpaTest 和 @AutoConfigureTestDatabase(replace = Replace.NONE)来使用“真实”数据库
@RunWith(SpringRunner.class)
@DataJpaTest (showSql = true )
@AutoConfigureTestDatabase(replace=Replace.NONE)
public class UserRepositoryTests {
@Autowired
private UserRepository userRepository;
....