Springboot项目中单元测试时注入bean失败的解决方案

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

Springboot项目中单元测试时注入bean失败的解决方案

柒的意志   2022-11-24 我要评论

Springboot项目中单元测试时注入bean失败

问题背景

最近公司项目搭了一个springboot项目进行开发,在单元测试时,由于生成项目后可能哪个同事把项目生产的test文件目录删了,也不知道是项目生成时test目录没有生成,需要自己建立一个test目录进行测试。

就是下图中的红框部分。。。

                                                                           

问题描述

在上图中的test目录建好之后写测试类的时候死活bean注入不成功,注意这里解决的问题是不考虑springboot版本等问题的

如遇到springboot版本的问题导致bean类无法注入到项目中,可能是注解和springboot版本不匹配导致启动类启动时扫描不到相应的bean类,这种错误的解法,网上一收一大把,这里就不在给写法了。。。

问题解决

也就是测试类的包名一定要和启动类的包名一致,包名必须一致!必须一致!一致!重要的话说三遍!!!

如果包名不一致,当启动类启动时就不知道去哪扫描bean,所以也就无法注入。

所以这里也给大家一个解决bean注入失败的思路:

1.首先检测测试类包名和启动类包名是否一致!

2.检查自己使用的注解是不是和当前springboot的版本一致。

3.检测开发代码中的bean类是否注入是正常的,然后再根据情况逐步排查。

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

我们在使用项目的时候,常常需求去单元测试,去测试我们写的接口是否可以正常运行。自己在练习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类可以去做接口调用。

以上为个人经验,希望能给大家一个参考,也希望大家多多支持。

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们