我对我的 Spring Boot 主要方法进行了以下测试。
测试尝试按预期启动应用程序 2 次。
第一次启动应用程序时,它使用 Mock 对象,第二次启动应用程序时,它调用实际的 bean。
我有 ReferenceDataService
具有 @PostConstract
方法调用,该方法调用对我在测试中不需要的其他应用程序进行其余调用。
另一件事是 MqConfiguration
尝试连接到 IBM 队列,我也希望在测试中避免这种情况。
请注意,即使我在测试类中添加了 @ComponentScan(excludeFilters...
,它也不会排除它。
在这种情况下,如何为我的主要方法编写测试?
@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 (The class to be tested)
@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);
}
}
最佳答案
可以将其分为两个单独的测试部分,因为我们应该努力在每个测试中测试单个功能(单一职责原则)。您可以像下面这样对测试进行建模:
@Test
public void applicationContextLoadedTest(){
}
@Test
public void applicationStartTest() {
//you can add your mocks as per your required dependencies and requirements
MainApplication.main(new String[] {});
}
或者,如果您被允许使用 PowerMockito,那么以下链接将为您提供验证静态调用的工作示例。 PowerMockito - SpringBoot test
关于spring-boot - Spring Boot Junit测试main方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57104790/