在普通java项目中,junit测试项目只需要在方法上直接使用@Test注解就可以运行了,但是在springmvc+spring的项目中使用junit4测试java web项目直接使用@junit注解是会报错的,因为我们难免会用到@Autowired注解,直接使用的话@Autowired注解的对象就会为null。
springmvc+spring+junit4这样的项目,是需要注入spring对象的,因此我们使用junit4时需要先使用@RunWith和@ContextConfiguration相关注解注入spring-context.xml里面的所有实例对象(你们的web项目可能不叫这个xml名字),下面来看看如何在spring项目中使用它。
1:首先引入junit4 maven的jar包,如下。
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.6.RELEASE</version> <scope>test</scope> </dependency>
2:添加一个junit测试类,例如MapperTest.java,如下。
package com.xfexp.examination.test;
import java.util.ArrayList;
import java.util.List;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import com.xfexp.exam.dao.AnswerMapper;
import com.xfexp.exam.model.Answer;
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring/spring-context.xml"})
public class MapperTest {
@Autowired
private AnswerMapper answerMapper;
@Test
public void test() {
List<Answer> list = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Answer answer = new Answer();
answer.setContent("dddddddddd"+i);
answer.setIsCorrect((short) 0);
answer.setQuestionId((long) 1);
list.add(answer);
}
int count = answerMapper.insertAnswers(list);
System.out.println("count="+count);
}
}