【发布时间】:2019-11-27 23:53:57
【问题描述】:
我对我的 Spring Boot 主要方法进行了以下测试。
测试尝试启动应用程序 2 次,这是预期的。
第一次启动应用程序时,它使用 Mock 对象,而第二次启动应用程序时,它调用实际的 bean。
我有ReferenceDataService 有@PostConstract 方法调用,它会调用我在测试中不想要的其他一些应用程序。
另一件事是MqConfiguration 尝试连接到 IBM 队列,我也想在测试中避免使用这些队列。
请注意,即使我在我的测试类中添加了@ComponentScan(excludeFilters...,它也不会排除它。
在这种情况下如何为我的 main 方法编写测试?
@ActiveProfiles(profiles = {"test"})
@RunWith(SpringRunner.class)
@SpringBootTest(classes = MainApplication.class, webEnvironment = WebEnvironment.RANDOM_PORT, properties = {
"camel.springboot.java-routes-include-pattern=**/NONE*"})
@EnableAutoConfiguration(exclude = {DataSourceAutoConfiguration.class, DataSourceTransactionManagerAutoConfiguration.class, SecurityAutoConfiguration.class})
@DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD)
@ComponentScan(excludeFilters = {@ComponentScan.Filter(type = FilterType.ASSIGNABLE_TYPE, value = {MqConfiguration.class, ReferenceDataCache.class})})
public class MainApplicationTest {
@MockBean
private MqService mqService;
@MockBean
private ReferenceDataService referenceDataService;
@SpyBean
private ReferenceDataCache cacheSpy;
@Test
public void test() {
Mockito.when(referenceDataService.getCurrencies()).thenReturn(new HashMap<>());
Mockito.when(referenceDataService.getFrequencies()).thenReturn(null);
Mockito.when(referenceDataService.getDayCountTypes()).thenReturn(null);
Mockito.when(referenceDataService.getBusinessDayConverntions()).thenReturn(null);
Mockito.when(referenceDataService.getRateDefinations()).thenReturn(null);
Mockito.when(referenceDataService.getBusinessCalendar()).thenReturn(null);
Mockito.when(referenceDataService.getFinancingTypes()).thenReturn(null);
Mockito.when(referenceDataService.getStaffs()).thenReturn(null);
MainApplication.main(new String[]{});
}
}
MainApplication.java(要测试的类)
@SpringBootApplication
@EnableJms
@EnableCaching
@AutoConfigureBefore(JmsAutoConfiguration.class)
public class MainApplication {
private static final Logger logger = LoggerFactory.getLogger(MainApplication.class);
public static void main(String[] args) {
SpringApplication.run(MainApplication.class, args);
}
}
【问题讨论】:
-
请发布您的所有代码,而不仅仅是其中的一部分。你说 ot 应该启动两次,但是你有一个测试调用一次 main 方法。
-
一个是我从测试中调用 main 方法,另一个是因为注释
@SpringBootTest(classes = MainApplication.class -
可以考虑拆分测试。就像第一个你可以为应用程序上下文加载和第二个你的应用程序上下文测试一样。或者,您是否允许使用 PowerMockito 来验证静态方法?
-
拆分单元测试和应用程序测试。
-
你能指出一些例子吗?或者你能给一些提示吗?我是第一次写junit。
标签: spring-boot junit spring-boot-test