若是咱們須要對咱們的Service方法做單元測試,剛好又是用Spring做爲IOC容器的,咱們能夠這麼配置Junit加載Spring容器,方便作單元測試。java
(1)引入所需的包spring
<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)寫測試類mybatis
測試類中要設置加載哪些Spring的配置(我這裏是「/config/application*.xml」),而後就能夠注入容器中的bean了。app
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); } }