gpt4 book ai didi

java - 与@SpringBootTest 一起使用时删除@DataJpaTest 的推荐方法

转载 作者:塔克拉玛干 更新时间:2023-11-02 19:44:40 25 4
gpt4 key购买 nike

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

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

@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
}

现在,我们遇到了以下错误:

NoSuchBeanDefinitionException: No bean named 'entityManagerFactory' available

根据this answer ,我们做了这样的事情:

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

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

最佳答案

测试类用@DataJpaTest 和@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。这是因为测试模块与所有其他模块(多 maven 模块项目)隔离。在 test-context.xml 中,我们为基础包定义了组件扫描。

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

关于java - 与@SpringBootTest 一起使用时删除@DataJpaTest 的推荐方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56459713/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com