Spring Boot 单元测试,注入失败,报空指针错误

我们在使用项目的时候,常常需求去单元测试,去测试我们写的接口是否可以正常运行.自己在练习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
來源:简书
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值