在没有 Spring Boot Application 主类的项目中测试 Spring Data Repository [英] Test Spring Data Repository in a project without a Spring Boot Application main class
问题描述
我有一个不包含运行 Spring Boot 应用程序的类的小项目.在那个类中,我只有一些配置和一些存储库.我想在小项目中测试这些存储库.
I have a small project that does not contain a class to run a Spring Boot Application. In that class I only have some configuration and some repositories. I would like to test those repositories inside the small project.
为此,我有以下几点:
@SpringBootTest
@DataJpaTest
public class TaskRepositoryTest extends AbstractTestNGSpringContextTests {
@Autowired
private TaskRepository taskRepository;
@Test
public void test() {
taskRepository.save(new Task("open"));
}
}
但我收到以下错误
Caused by: java.lang.NoSuchMethodError: org.springframework.boot.jdbc.DataSourceBuilder.findType(Ljava/lang/ClassLoader;)Ljava/lang/Class;
知道我必须做什么吗?
推荐答案
这适用于 Spring Boot 2.0.3、H2 和最新的 RELEASE testng:
This works for me with Spring Boot 2.0.3, H2 and latest RELEASE testng:
@EnableAutoConfiguration
@ContextConfiguration(classes = TaskRepository.class)
@DataJpaTest
public class TaskTest extends AbstractTestNGSpringContextTests {
@Autowired
private TaskRepository taskRepository;
@Test
public void test() {
taskRepository.save(new Task("open"));
}
}
<小时>
LE:
在以前版本的答案中,我使用了 @SpringBootTest @DataJpaTest
但这似乎是错误的方法.将出现以下消息:
In the previous version of the answer I've used @SpringBootTest @DataJpaTest
but that seems to be the wrong way to do it.
The following message would appear:
[main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - 没有为测试类 [one.adf.springwithoutapp.TaskTest] 找到 @ContextConfiguration 和 @ContextHierarchy,使用 SpringBootContextLoader
[main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - Neither @ContextConfiguration nor @ContextHierarchy found for test class [one.adf.springwithoutapp.TaskTest], using SpringBootContextLoader
将 @ContextConfiguration
与 @DataJpaTest
一起使用可消除该警告,并且 IntelliJ 不会将模拟的 taskRepository
标记为 无法自动装配.未找到TaskRepository"类型的 bean.
Using @ContextConfiguration
with @DataJpaTest
removes that warning and IntelliJ doesn't mark the mocked taskRepository
as Could not autowire. No beans of 'TaskRepository' type found.
这篇关于在没有 Spring Boot Application 主类的项目中测试 Spring Data Repository的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!