在没有 Spring Boot Application 主类的项目中测试 Spring Data Repository

Man*_*rte 5 testng spring-data-jpa spring-boot

我有一个不包含运行 Spring Boot 应用程序的类的小项目。在那个类中,我只有一些配置和一些存储库。我想在小项目中测试这些存储库。

为此,我有以下几点:

@SpringBootTest
@DataJpaTest
public class TaskRepositoryTest extends AbstractTestNGSpringContextTests {

    @Autowired
    private TaskRepository taskRepository;

    @Test
    public void test() {
        taskRepository.save(new Task("open"));
    }
}
Run Code Online (Sandbox Code Playgroud)

但我收到以下错误

Caused by: java.lang.NoSuchMethodError: org.springframework.boot.jdbc.DataSourceBuilder.findType(Ljava/lang/ClassLoader;)Ljava/lang/Class;
Run Code Online (Sandbox Code Playgroud)

知道我必须做什么吗?

And*_*ete 6

这适用于 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"));
   }

}
Run Code Online (Sandbox Code Playgroud)

乐:

在我使用过的先前版本的答案中,@SpringBootTest @DataJpaTest但这似乎是错误的方法。将出现以下消息:

[main] INFO org.springframework.boot.test.context.SpringBootTestContextBootstrapper - 使用 SpringBootContextLoader 找不到测试类 [one.adf.springwithoutapp.TaskTest] 的 @ContextConfiguration 和 @ContextHierarchy

使用@ContextConfigurationwith@DataJpaTest会删除该警告,并且 IntelliJ 不会将模拟标记taskRepository无法自动装配。未找到“TaskRepository”类型的 bean。