SpringBoot Junit测试主要方法

时间:2019-07-19 02:31:25

标签: spring-boot junit spring-boot-test

我的spring boot main方法有以下测试。

该测试尝试启动应用程序两次,这是预期的。

第一次启动应用程序时,它将使用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(要测试的类)

@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);
    }

}

1 个答案:

答案 0 :(得分:1)

一个人可以将它分为两​​个独立的测试部分,因为我们应该努力为每个测试测试一个功能(单一职责原则)。您可以像下面那样对测试进行建模:

 @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