标签:
如果我们需要对我们的Service方法作单元测试,恰好又是用Spring作为IOC容器的,我们可以这么配置Junit加载Spring容器,方便做单元测试。
(1)引入所需的包
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>3.2.10.RELEASE</version> </dependency>
(2)写测试类
测试类中要设置加载哪些Spring的配置(我这里是“/config/application*.xml”),然后就可以注入容器中的bean了。
package com.nicchagil.mybatis3spring3intg.junit; 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.nicchagil.mybatis3spring3intg.bean.User; import com.nicchagil.mybatis3spring3intg.service.UserService; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/config/application*.xml"}) public class JunitTest { @Autowired private UserService userService; @Test public void c1() { List<User> userList = userService.query(new User()); System.out.println(userList); } }
常用的方式是将加载配置的部分公用出来:
package com.nicchagil.mybatis3spring3intg.junit; import org.junit.runner.RunWith; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({"/config/application*.xml"}) public class BaseJunit { }
然后需要的各个测试类继承公用类:
package com.nicchagil.mybatis3spring3intg.junit; import java.util.List; import org.junit.Test; import org.springframework.beans.factory.annotation.Autowired; import com.nicchagil.mybatis3spring3intg.bean.User; import com.nicchagil.mybatis3spring3intg.service.UserService; public class UserServiceTest extends BaseJunit { @Autowired private UserService userService; @Test public void c1() { List<User> userList = userService.query(new User()); System.out.println(userList); } }
标签:
原文地址:http://www.cnblogs.com/nick-huang/p/5645249.html