场景:由于业务需要,需要对编写的接口进行测试,项目使用springboot+mybatis,jdk1.7 ,但是使用@Test发现service层代码会出现空指针异常,便简单学习了下。下面说说我的解决办法
1.使用@SpringbootTest+@RunWith
import com.geostar.zrzy.zwfw.service.BdcYbdyhService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
/**
* @Description:
* @Author:ay
* @Date:2020/10/15
*/
@SpringBootTest
@RunWith(SpringRunner.class)
public class Testdaf {
@Autowired
BdcYbdyhService bdcYbdyhService ;
@Test
public void testZhujie(){
System.out.println( bdcYbdyhService.getBdcdyh("****"));
}
}
注意事项:
需要引入的依赖,经过本人测试,发现jdk1.7支持以下版本
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
<version>1.5.9.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.13.RELEASE</version>
</dependency>
2.思考
如果仅仅使用@Test注解,会出现空指针异常,具体原因我觉得就是bean没有注入,那么需要手动注入