如果我們需要對我們的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);
}
}