刚学spring框架,习惯了以前的struts环境下的单元测试,发现在用以前的方法却报错了,后来请教大佬,可以使用如下方法进行spring环境下的单元测试:
问题描述:spring环境中,进行service层单元测试时,错误提示信息显示没有xxxService的 bean name。
解决方法:
1.引入依赖
<!--单元测试的jar包,如果使用spring注解测试版本至少是4.12-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>4.3.10.RELEASE</version>
</dependency>
2.在测试类上添加注解。
@RunWith(SpringJUnit4ClassRunner.class)//表示使用spring测试
@ContextConfiguration("classpath:applicationContext.xml")//spring配置文件的路径
public class TestService {
@Autowired
private StudentService ss;
@Test
public void testStudentService(){
List<Student> students = ss.selectAll();
students.forEach(System.out::println);
}
@Test
public void testStudentService2(){
PageInfo<Student> pi = ss.selectByPage(1,5);
pi.getList().forEach(System.out::println);
}
}