繁体   English   中英

Spring启动测试没有从src / main / resources中获取hbm.xml文件

[英]Spring boot test not picking up hbm.xml files from src/main/resources

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

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

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

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

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

我们得到:

命名查询未找到异常

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

@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文件复制, hbm.xml正确拾取hbm.xml文件并正确运行测试。

无论如何,直接从src/main/resouces文件夹中获取xml文件,我们不必复制这些文件?

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

以下是我的情况:

我的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文件的基础。 这可能与类加载器有关

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM