加载Spring Boot应用程序测试属性时遇到问题,我的application.properties文件包含在src / test / resources /下,但是当我运行测试用例时,由于无法加载应用程序而失败上下文。这是我的测试班级
@SpringBootTest
@EmbeddedKafka(partitions = 1, controlledShutdown = true)
@Import(KafkaTestConfiguration.class)
@EnableAutoConfiguration(exclude = IntegrationAutoConfiguration.class)
public class DeadLetterPropertiesTest {
@Autowired
DeadLetterProperties deadLetterProperties;
@Value("errorqueue")
private String deadLetterQueueName;
@Test
public void queueNameTest() {
assertEquals(deadLetterQueueName,deadLetterProperties.getQueueName());
}
}
这是堆栈跟踪,如下所示:
java.lang.NullPointerException at
com.test.DeadLetterPropertiesTest.queueNameTest(DeadLetterPropertiesTest.java:47) at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method) at
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62) at
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43) at
java.lang.reflect.Method.invoke(Method.java:498) at
org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50) at
org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12) at
org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47) at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17) at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78) at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57) at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290) at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71) at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288) at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58) at
org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268) at org.junit.runners.ParentRunner.run(ParentRunner.java:363) at org.junit.runner.JUnitCore.run(JUnitCore.java:137) at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68) at com.intellij.rt.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:33) at com.intellij.rt.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:230) at com.intellij.rt.junit.JUnitStarter.main(JUnitStarter.java:58)
答案 0 :(得分:0)
stacktrace确认在测试过程中创建应用程序上下文失败。可能是由于以下几种原因导致无法从application.properties
读取值。我在您的代码中注意到了几个问题。如果按照文档使用@ContextConfiguration
注释,则可以在代码中删除@SpringBootTest
注释:
Spring Boot提供了@SpringBootTest批注,该批注可用作 标准弹簧测试@ContextConfiguration的替代方法 需要Spring Boot功能时使用注解。注释的作者 通过创建测试中使用的ApplicationContext SpringApplication。
@TestConfiguration
。您还应该排除
常规配置类,因为如果您使用
为相同的bean提供单独的测试配置。application.properties
和测试值
在src/test/resources
下,则无需您指定
使用@TestPropertySource
作为文件的路径将是
在测试过程中被springboot自动占用。@SpringBootTest
和@RunWith(SpringRunner.class)
来代替。这些都是针对不同用例的不同注释。如果您不了解使用Link 官方doc
为进一步分析,请更正您的代码,然后再次运行,如果错误仍然存在,请共享完整的堆栈跟踪。