【发布时间】:2021-08-04 20:10:15
【问题描述】:
我正在为 Spring Boot 应用程序编写控制器测试。要使用 spring 应用程序上下文,我正在使用 SpringRunner 类。 问题是主应用程序类有一个属性源定义到特定文件路径。
当我运行测试时,我从硬编码文件中得到一个 FileNotFound 异常。我希望我的测试独立于这个属性源。
我无法在主应用程序中为属性源添加“ignoreResourceNotFound”选项。
下面是定义了属性源的主应用程序类。
@SpringBootApplication
@PropertySource("file:/opt/system/conf/smto/management.properties")
@EnableConfigurationProperties
public class ManagementApp {
public static void main(String[] args) {
SpringApplication.run(ManagementApp.class, args);
}
}
我也在下面添加我的测试类
@RunWith(SpringRunner.class)
@TestPropertySource(locations = {"classpath:application.properties","classpath:management.properties"})
@DirtiesContext
@EmbeddedKafka(topics = {"management-dev"},partitions = 1,
controlledShutdown = false,brokerProperties = {"listeners=PLAINTEXT://localhost:9092", "port=9092"})
@AutoConfigureMockMvc
@WebMvcTest(Controller.class)
public class ControllerTest {
}
【问题讨论】:
-
您好,欢迎您! This 并不是真正的“重复”,但 accepted answer 也是解决您问题的方法。 (你会像
@ActiveProfiles("override")一样“装饰”你的测试。) -
嗨,谢谢@xerx593!我尝试使用
@ActiveProfiles("override"),但主要配置类仍在寻找相同的文件。我所做的更改是,将测试类移动到旧包(因此可以找到主应用程序),在测试类上添加@ActiveProfile("override),并创建 override.properties。同样的错误
标签: spring spring-boot spring-mvc spring-boot-test spring-test-mvc