引入单元测试的sdk
1 2 3 4 5 6
| <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>RELEASE</version> <scope>test</scope> </dependency>
|
注解式配置,代码如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
| package com.geping.etl.service;
import com.geping.etl.baseeast.service.checkManage.CheckRuleService; import lombok.extern.slf4j.Slf4j; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration;
@RunWith(SpringJUnit4ClassRunner.class) @SpringBootTest @WebAppConfiguration @Slf4j public class CheckRuleServiceTest {
@Autowired private CheckRuleService checkRuleService;
@Test public void importXlsxFileTest(){ log.info("importXlsxFileTest start ========"); checkRuleService.importXlsxFile(); log.info("importXlsxFileTest end ========"); }
}
|
启动单元测试,能正常注入spring声明的bean,如下图:

编程式,代码如下:
使用AnnotationConfigEmbeddedWebApplicationContext对象加载获取spring的IOC容器,从而获得spring的bean
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
| package com.geping.etl.service;
import com.geping.etl.DataETLApplication; import com.geping.etl.baseeast.service.checkManage.CheckRuleService; import com.geping.etl.baseeast.service.impl.checkManage.CheckRuleServiceImpl; import org.junit.Test; import org.springframework.boot.context.embedded.AnnotationConfigEmbeddedWebApplicationContext; import org.springframework.context.ApplicationContext;
public class CheckRuleCodeServiceTest {
@Test public void importXlsxFileTest(){ ApplicationContext applicationContext = new AnnotationConfigEmbeddedWebApplicationContext(DataETLApplication.class); CheckRuleService checkRuleService = applicationContext.getBean(CheckRuleServiceImpl.class); checkRuleService.importXlsxFile();
} }
|
还需要java config,配置application文件的加载,代码如下
1 2 3 4 5 6 7 8 9 10 11
| package com.geping.etl.service;
import org.springframework.context.annotation.Configuration; import org.springframework.context.annotation.PropertySource; import org.springframework.test.context.web.WebAppConfiguration;
@PropertySource(value = {"classpath:/application.properties"}) @Configuration public class ApplicaitonConfig { }
|
启动单元测试,能正常注入spring声明的bean,如下图:
