在使用Junit进行单元测试的时候有可能会需要使用@Autowired或者@Resource进行注入或者装配,但是单纯的使用Junit进行这些操作时会报NullPointerExecption,因为这样无法使用spring容器中的资源,我们知道@Autowired和@Resource装配注入的资源都在spring容器中,那怎么才能成功装配注入进来呢?
第一步:配置需要使用的依赖包:
<!--spring的测试包:SpringRunner和@RunWith在这个包中-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<scope>compile</scope>
</dependency>
<!--spring的测试包:@SpringBootTest在这个包中-->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-test</artifactId>
</dependency>
<!--@Test在这个包中-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
</dependency>
第二步:使用spring容器中的资源
代码:
import org.apache.log4j.Logger;
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.data.redis.core.RedisTemplate;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class SpringTestDemo {
private final Logger logger = Logger.getLogger(SpringTestDemo.class);
@Autowired
private RedisTemplate<String,String> redisTemplate;
@Test
public void set(){
logger.info("已经连接上redis开始写入数据!");
redisTemplate.opsForValue().set("myKey","myValue");
System.out.println(redisTemplate.opsForValue().get("myKey"));
}
}