找不到@SpringBootConfiguration
Unable to find a @SpringBootConfiguration
我想为此私有方法创建一个 JUnit 测试:
@Component
public class ReportingProcessor {
@EventListener
private void collectEnvironmentData(ContextRefreshedEvent event) {
}
}
我试过这个:
@ContextConfiguration
@SpringBootTest
public class ReportingTest {
@Autowired
ReportingProcessor reportingProcessor;
@Test
public void reportingTest() throws Exception {
ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);
}
}
当我 运行 我得到的代码:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
你知道我可以解决这个问题吗?
您应该将 @RunWith
与您的 @SpringBootTest
一起使用:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReportingTest {
@Autowired
ReportingProcessor reportingProcessor;
@Test
public void reportingTest() throws Exception {
ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);
}
}
如果您没有使用@SpringBootApplication 和已知的 main() 方法注释任何 class,则需要在 @SpringBootTest 注释上定位您的组件 class。
通常我在构建库时这样做,对于某些特定场景,我需要有 spring 上下文来对它们进行单元测试。
只需将此添加到您的代码中:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ReportingProcessor.class)
public class ReportingTest {
...
刚刚做了,测试是运行。
编辑:不知道你到底想测试什么,只是想展示你如何修复你遇到的错误。
我想为此私有方法创建一个 JUnit 测试:
@Component
public class ReportingProcessor {
@EventListener
private void collectEnvironmentData(ContextRefreshedEvent event) {
}
}
我试过这个:
@ContextConfiguration
@SpringBootTest
public class ReportingTest {
@Autowired
ReportingProcessor reportingProcessor;
@Test
public void reportingTest() throws Exception {
ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);
}
}
当我 运行 我得到的代码:
java.lang.IllegalStateException: Unable to find a @SpringBootConfiguration, you need to use @ContextConfiguration or @SpringBootTest(classes=...) with your test
你知道我可以解决这个问题吗?
您应该将 @RunWith
与您的 @SpringBootTest
一起使用:
@RunWith(SpringRunner.class)
@SpringBootTest
public class ReportingTest {
@Autowired
ReportingProcessor reportingProcessor;
@Test
public void reportingTest() throws Exception {
ContextRefreshedEvent contextRefreshedEvent = PowerMockito.mock(ContextRefreshedEvent.class);
Whitebox.invokeMethod(reportingProcessor, "collectEnvironmentData", contextRefreshedEvent);
}
}
如果您没有使用@SpringBootApplication 和已知的 main() 方法注释任何 class,则需要在 @SpringBootTest 注释上定位您的组件 class。
通常我在构建库时这样做,对于某些特定场景,我需要有 spring 上下文来对它们进行单元测试。
只需将此添加到您的代码中:
@RunWith(SpringRunner.class)
@SpringBootTest(classes = ReportingProcessor.class)
public class ReportingTest {
...
刚刚做了,测试是运行。
编辑:不知道你到底想测试什么,只是想展示你如何修复你遇到的错误。