4. SpringBoot —— 单元测试
首先在pom文件中引入spring-boot-starter-test
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
</dependency>
测试方式1:
这也是官方推荐的方式,缺点是在真正的多项目开发时,有的项目没有启动类,为了这种方式的测试,还需在 src/test 下构建一个测试启动类
@RunWith(SpringRunner.class) @SpringBootTest(classes=App.class) public class RedisUtilTest { @Autowired private RedisUtil redisUtil ; @Test public void testAddOrUpdate() { redisUtil.addOrUpdate("test","ddd"); } }
测试方式2 (人个总结出的方法):
使用 SpringApplicationBuilder 类构建 ApplicationContext实例,但是这种方式需要明确知道相应的@Configuration配置类
1. 定义项目的Configuration类,相当于指定了配置文件
@Configuration @ConditionalOnMissingBean(RedisUtil.class) public class EcshopCommonUtilsConfig { @Bean public RedisUtil redisUtil() { return new RedisUtil() ; } }
2.通过SpringApplicationBuilder构建context容器
public class RedisUtilTest { @Autowired private RedisUtil redisUtil ; @Before public void init() { Class<?>[] sources = {XxxxConfig.class,RedisAutoConfiguration.class} ; String[] properties = {"spring.redis.host=127.0.0.1","spring.redis.port=6379","spring.redis.database=0","spring.redis.password=xxx"} ; SpringApplicationBuilder builder = new SpringApplicationBuilder().properties(properties) .web(WebApplicationType.NONE) ; builder.sources(sources) ; ConfigurableApplicationContext context = builder.run() ; this.redisUtil = context.getBean(RedisUtil.class) ; } @Test public void testAddOrUpdate() { redisUtil.addOrUpdate("test","ddd"); } }