【问题标题】:Spring boot test not picking up hbm.xml files from src/main/resourcesSpring Boot 测试未从 src/main/resources 中获取 hbm.xml 文件
【发布时间】:2017-04-04 14:00:26
【问题描述】:

我们有一个 spring-boot 版本 1.5.2.RELEASE 的项目。

我们需要在 xml 中处理 hibernate 命名查询(java 注释中的命名查询不是我们的选择)。

为此,我们将所有hbm.xml 文件(包含这些命名查询)添加到src/main/resources 目录中。

当我们的应用程序运行时,这不是问题。命名查询被正确提取。

但是,当我们编写集成测试用例时,它无法识别命名查询。

我们得到:

未找到命名查询异常

下面是我们的测试用例代码:

@RunWith(SpringRunner.class)
@SpringBootTest( webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
public class MyIntegrationTest {
    @Autowired
    private TestRestTemplate template;

    @Test 
    public void checkRestService() throws Exception {
        ResponseEntity<String> response = template.getForEntity("/hello/1", String.class);
        assertTrue(response.getStatusCodeValue() == 200);
    }
}

如果我们将hbm.xml 文件复制到src/test/resources directory 中,则hbm.xml 文件会被正确拾取并且测试会正确运行。

有没有直接从src/main/resouces文件夹中提取xml文件而我们不必复制这些文件?

【问题讨论】:

  • 一个asked question 可以帮助你。
  • 感谢您发布类似问题的链接。但是,我们能够在主应用程序中正确使用 Hibernate SessionFactory 并使用来自 hbm.xml 文件的命名查询。问题只出在编写集成测试用例时。

标签: java spring-boot spring-data-jpa spring-boot-test


【解决方案1】:

我在 Spring Boot 2.1.3 中遇到了与您相同的问题,并通过将 application.properties 文件从 src/test/resources 文件夹移动到 src/main/resources 文件夹并将其重命名为 application-test.properties 来解决/p>

以下是我的情况:

我的 Spring Boot 2.1.3 应用程序具有以下文件夹结构:

src/main
     +-- java (applcation java files)
     +-- resources
            +-- hibernate/MyMapping.hbm.xml
            +-- hibernate/MyMapping2.hbm.xml
            +-- application.properties (define the default / base attributes needed for my application)
            +-- application-dev.properties (define the development environment settings)
src/test
    +-- java (testing java files)
    +-- resources
            +-- application.properties (define the testing attributes)

每当我在 Eclipse / maven 中运行测试用例时,总会出现错误:

未找到命名查询异常

我通过以下方式解决了这个问题:

  1. 将 src/test/resources/application.properties 文件移动到 src/main/resources/application-test.properties
  2. 在 src/main/resources/application.properties 中,定义以下属性:
spring.jpa.mapping-resources=hibernate/MyMapping.hbm.xml,hibernate/MyMapping2.hbm.xml
  1. 将注解@ActiveProfile("test")添加到所有测试类中,使其首先加载src/main/resources文件夹中的application-test.properties文件

在此之后,我的 SpringBoot 2 应用程序的测试用例可以在 Eclipse 和 maven 命令行中毫无问题地运行。

我的直觉是 Spring Boot/Hibernate 使用第一个加载的 application.properties 的位置作为基础来扫描/定位所有 hbm 文件。这可能与类加载器有关

【讨论】:

    猜你喜欢
    • 2020-07-24
    • 2017-02-05
    • 2014-04-01
    • 2015-02-26
    • 2016-01-30
    • 2015-03-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多