我有一个不包含运行 Spring Boot 应用程序的类的小项目。在那个类中,我只有一些配置和一些存储库。我想在小项目中测试这些存储库。
为此,我有以下几点:
@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:
@EnableAutoConfiguration
@ContextConfiguration(classes = TaskRepository.class)
@DataJpaTest
public class TaskTest extends AbstractTestNGSpringContextTests {
@Autowired
private TaskRepository taskRepository;
@Test
public void test() {
taskRepository.save(new Task("open"));
}
}
乐:
在之前版本的答案中,我使用了
@SpringBootTest @DataJpaTest
但这似乎是错误的做法。将出现以下消息:
[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
因为无法 Autowiring 。未找到“TaskRepository”类型的 bean。
关于spring-boot - 在没有 Spring Boot Application 主类的项目中测试 Spring Data Repository,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50231209/