我们在使用项目的时候,常常需求去单元测试,去测试我们写的接口是否可以正常运行.自己在练习Spring Boot 搭建 Redis的时候进行测试.下面是测试类.
/**
* @author jins
* @date on 2018/5/6.
*/
@RunWith(SpringJUnit4ClassRunner.class)
public class RedisTest {
@Autowired
private StringRedisTemplate stringRedisTemplate;
@Test
public void redisTest(){
stringRedisTemplate.opsForValue().set("ceshi","redis");
System.out.println(stringRedisTemplate.opsForValue().get("ceshi"));
}
}
运行的时候发现,直接会报NullPointException,或者是No bean.比较疑惑,自己想这应该是spring 容器里面没有注入Bean导致的,我们没有从spring 容器中拿到 StringRedisTemplate Bean 所以会报错.然后自己去网上看了一下,缺少了注解 @SpringBootTest ,自己看了下文档.这里点进去注解显示以下内容.看了内容知道,通过@SpringBootTest注解,给我们提供了Spring容器管理.加上之后,可以运行.
Annotation that can be specified on a test class that runs Spring Boot based tests.
Provides the following features over and above the regular Spring TestContext
Framework:
注解制定了一个测试类运行了Spring Boot环境。提供了以下一些特性:
Uses SpringBootContextLoader as the default ContextLoader when no specific ContextConfiguration#loader() @ContextConfiguration(loader=...) is defined.
当没有特定的ContextConfiguration#loader()(@ContextConfiguration(loader=...))被定义那么就是SpringBootContextLoader作为默认的ContextLoader。
Automatically searches for a SpringBootConfiguration @SpringBootConfiguration when nested @Configuration is not used, and no explicit #classes() classes are
specified.
自动搜索到SpringBootConfiguration注解的文件。
Allows custom Environment properties to be defined using the properties() properties attribute}.
允许自动注入Environment类读取配置文件。
Provides support for different #webEnvironment() webEnvironment modes,
including the ability to start a fully running container listening on a
WebEnvironment#DEFINED_PORT defined or WebEnvironment#RANDOM_PORT
random port.
提供一个webEnvironment环境,可以完整的允许一个web环境使用随机的端口或者自定义的端口。
Registers a org.springframework.boot.test.web.client.TestRestTemplate
TestRestTemplate bean for use in web tests that are using a fully running container.
注册了TestRestTemplate类可以去做接口调用。
作者:二月_春风
链接:https://www.jianshu.com/p/72b19e24a602
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。