与@SpringBootTest 一起使用时删除@DataJpaTest 的推荐方法 [英] Recommended way to remove @DataJpaTest when used along with @SpringBootTest

查看:115
本文介绍了与@SpringBootTest 一起使用时删除@DataJpaTest 的推荐方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个依赖 Spring Boot 2.0 的应用程序.我们正在将其从 JDK8 迁移到 JDK11.这也使我们能够将 Spring Boot 从 2.0 更新到 2.1.阅读变更日志后,我们似乎需要进行任何重大变更.

We have an application that relies on Spring Boot 2.0. We are in the process of migrating it to JDK11 from JDK8. This also enabled us to update Spring Boot from 2.0 to 2.1. After reading through the changelog, it appeared there was any major change that needed for us.

现在的问题在于某些测试类同时使用@SpringBootTest@DataJpaTest 进行注释.根据 this 和和文档一样,我们不应该同时使用两者,而是将 @DataJpaTest 更改为 @AutoConfigureTestDatabase.代码如下:

Now the problem lies in where some test classes are annotated with both @SpringBootTest and @DataJpaTest. As per this and as well as the documentation, we are not supposed to use both together and instead we changed @DataJpaTest to @AutoConfigureTestDatabase. Here is how the code is:

@RunWith(SpringRunner.class)
@SpringBootTest(classes = {A.class, B.class}, properties = {
    "x=xxx",
    "y=yyy"
})
@AutoConfigureTestDatabase  // Used to be @DataJpaTest
@EnableJpaRepositories("com.test")
@EntityScan("com.test")
public class Test {

    @TestConfiguration
    public static class TestConfig {
        // Some beans returning
    }
    // Tests
}

现在,我们最终得到以下错误:

Now, we end up with the following error:

NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

因此根据 这个答案,我们做了这样的事情:

So as per this answer, we did something like this:

@EnableJpaRepositories(basePackages="com.test", entityManagerFactoryRef="entityManagerFactory")

即使在这之后,我们仍然以同样的错误告终.这是删除 @DataJpaTest 的正确方法吗?或者我们是否需要删除 @SpringBootTest 并做其他事情?任何形式的指导都非常感谢.

Even after this we still end up with the same error. Is this the right way to remove @DataJpaTest? Or do we need to remove @SpringBootTest and do something else? Any sort of guidance is much appreciated.

推荐答案

测试类用@DataJpaTest 和@ContextConfiguration 注释

The testclass is annotated with @DataJpaTest and @ContextConfiguration

@RunWith(SpringRunner.class)
@DataJpaTest
@ContextConfiguration(locations = { "classpath:test-context.xml" })
public abstract class AbstractTestCase {

    protected static final Logger LOG = LoggerFactory.getLogger(AbstractTestCase.class);

}

我们定义了一个 test-context.xml.这是因为 testmodule 与所有其他模块(多 Maven 模块项目)隔离.在 test-context.xml 中,我们为基础包定义了组件扫描.

We defined a test-context.xml. This is because the testmodule is isolated from all other modules (multi maven module project). In the test-context.xml we defined the component-scan for the base-package.

<context:component-scan base-package="de.example.base.package" />

这篇关于与@SpringBootTest 一起使用时删除@DataJpaTest 的推荐方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆