繁体   English   中英

Spring 引导“TestPropertySource”不工作

[英]Spring Boot `TestPropertySource` not Working

我有一个简单的单元测试,我希望单元测试加载我放在src/test/resources/test.properties中的测试属性文件,而不是src/main/resources/application.properties中的属性文件src/main/resources/application.properties

我的测试class设置如下:

@RunWith(SpringRunner.class)
@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
@AutoConfigureMockMvc
@TestPropertySource(locations = "classpath:src/test/resources/properties-test.yml")
public class SecurityConfigurationTest {
    @MockBean
    KafkaConfiguration kafkaConfiguration;

    @MockBean
    KafkaMonitor kafkaMonitor;

    @MockBean
    BuildProperties buildProperties;

    @Autowired
    MockMvc mockMvc;

    @Test
    public void unauthorizedUser_shouldNotAccessHomePage() throws Exception{
        mockMvc
                .perform(get("/"))
                .andExpect(status().isUnauthorized());
    }

}

我的工程文件结构如下图: 在此处输入图像描述

但是我收到以下错误,提示我没有正确指定此属性文件:

Caused by: java.io.FileNotFoundException: class path resource [src/test/resources/test.properties] cannot be opened because it does not exist

我怎样才能设法让我的单元测试使用test.properties文件而不是application.properties文件?

在 pom.xml 中添加一个profiles 标签,指定程序在运行时应该选择哪个属性文件。

 <profiles>
    <profile>
        <id>test</id>
        <properties>
            <activatedProperties>test</activatedProperties>
        </properties>
        <activation>
            <activeByDefault>true</activeByDefault>
        </activation>
    </profile>
</profiles>

注意:您的属性文件的名称必须是application-test.properties

这将使您的测试属性处于活动状态,但要访问它,您需要配置测试资源文件夹并让 intellij 知道“在运行时使用它”。

在 Intellij 中,您可以更改用于运行项目的资源文件夹,因此您需要......

  1. Select 测试资源文件夹。
  2. 右键单击它。 在打开的菜单中,select Modify Run Configuration新建一个配置。

这意味着为运行测试资源文件夹创建了一个新的运行配置

  1. 运行配置。

Maven 默认会将 package src/test/resources/文件夹下的所有文件放到类路径下。 所以要通过类路径引用它,它应该是:

@TestPropertySource(locations = "classpath:test.properties") 

或者,如果你想通过系统文件路径引用它,你可以将其更改为:

@TestPropertySource(locations = "file:src/test/resources/test.properties") 

在幕后,它使用ResourceLoader来加载文件。 有关更多详细信息,请参阅内容。

暂无
暂无

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

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