单元测试service注解注入,会空指针异常

简介: 单元测试service注解注入,会空指针异常

单元测试service注解注入,会空指针异常但是用getBean方式则可以获取到service

因为注解是spring容器解析的,注解能够生效的话是需要spring容器启动的,就是web项目启动环境下使用的。

在junit里面测试,要想让Spring容器管理bean完成自动注入的话,可以使用Spring的junit测试工具注解。代码如下:

import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.test.context.transaction.TransactionConfiguration;
import javax.annotation.Resource;
import junit.framework.TestCase;
import com.sinopec.carlife.model.Region;
import com.sinopec.carlife.service.api.RegionService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations ={"classpath:spring/spring.xml"})
@Transactional
public class RegionServiceTest extends TestCase {
    @Resource(name="regionService")
    private RegionService regionService;
    @Test
    public void testFindRegions() {
        try {
            List<Region> regions = regionService.findRegions();
            System.out.println(regions.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

这样就能使用spring自动为junit单元测试自动注入依赖了。

相关文章
|
4月前
|
前端开发 Java 测试技术
JavaSE碎碎念:记录一次异常测试和一些个人的浅显理解
JavaSE碎碎念:记录一次异常测试和一些个人的浅显理解
|
10天前
|
Java 测试技术
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
SpringBoot整合单元测试&&关于SpringBoot单元测试找不到Mapper和Service报java.lang.NullPointerException的错误
16 0
|
3月前
|
Kubernetes 关系型数据库 MySQL
seata启动问题之指针异常如何解决
Seata是一款开源的分布式事务解决方案,旨在提供高效且无缝的分布式事务服务;在集成和使用Seata过程中,开发者可能会遇到不同的异常问题,本合集针对Seata常见异常进行系统整理,为开发者提供详细的问题分析和解决方案,助力高效解决分布式事务中的难题。
65 0
|
29天前
|
缓存 NoSQL Redis
@Autowired注入RedisCache报错空指针
@Autowired注入RedisCache报错空指针
13 0
|
29天前
|
Java 计算机视觉
java实现人脸识别源码【含测试效果图】——Service层(IUserService)
java实现人脸识别源码【含测试效果图】——Service层(IUserService)
13 1
|
30天前
javaWeb服务详解(含源代码,测试通过,注释) ——Emp的Service层
vjavaWeb服务详解(含源代码,测试通过,注释) ——Emp的Service层
5 0
|
30天前
javaWeb服务详解(含源代码,测试通过,注释) ——Dept的Service层
javaWeb服务详解(含源代码,测试通过,注释) ——Dept的Service层
7 0
项目中常见NPE空指针异常
项目中常见NPE空指针异常
|
2月前
|
Java Spring
Spring 使用注解注入失败,调用内容时提示空指针
Spring 使用注解注入失败,调用内容时提示空指针
14 0
|
2月前
|
安全 IDE Java
终结空指针异常:Java开发者的生存指南
终结空指针异常:Java开发者的生存指南
58 1