0

如何从“application-test.properties”之类的文件中加载测试属性?

该文件存储在 src/test/resources 文件夹中。我也将文件放在所有可能的文件夹中。当作为 Maven 测试运行的一部分运行测试时,一切正常。从(IntelliJ)IDE 运行新的(单个)测试时,每次我收到相同的错误消息:

原因:java.io.FileNotFoundException:类路径资源[application-test.properties]无法打开,因为它不存在

这是测试类:

@RunWith(SpringRunner.class)
@EnableAutoConfiguration
@ComponentScan(basePackages = {"nl.deholtmans.tjm1706.todolist"})
@PropertySource( "application-test.properties")
public class TodoListServiceTest {
    @Autowired
    TodoListService todoListService;
    @Test
    public void testBasic() { ... }

看来我必须第一次从 Maven 运行测试。这是为什么?

4

1 回答 1

1

如果配置文件被激活,Spring Boot 将自动加载正确的属性文件。在测试中,您可以@ActiveProfiles为此使用注释。

接下来,您需要确保您实际使用正确的 Spring Boot 基础设施来运行您的测试,使用@SpringBootTest. 话虽如此,您的测试标头应该如下所示

@RunWith(SpringRunner.class)
@SpringBootTest
@ActiveProfiles("test")
public class TodoListServiceTest { ... }

当然,请确保您的 IDE 在运行测试之前构建应用程序。

于 2019-05-20T09:40:17.290 回答