一、普通的单元测试:
在 Spring 中我们将 bean 交给 Spring IOC 容器管理,那么我们在需要使用 bean 时,也要去 IOC 容器中获取,因此我们需要先获取 IOC 容器对象,再从容器中获取我们需要的 bean,就如下面一样。
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import cn.edu.pzhu.cg.entities.Employee;
import cn.edu.pzhu.onlineshopping.bean.Customer;
import cn.edu.pzhu.onlineshopping.service.CustomerService;
public class TestClass {
private CustomerService customerService;
private ApplicationContext ctx;
@Before
public void init() {
ctx = new ClassPathXmlApplicationContext("applicationContext.xml");
customerService = (CustomerService) ctx.getBean("customerService");
}
@Test
public void checkUserName() {
String name = "Jack";
System.out.println(customerService.getCustomerByName(name));
}
@Test
public void testAddCustomer() {
Customer cus = new Customer(null, "Tom", "111", 0, "123", "null", null, null, null);
customerService.addCustomer(cus);
}
}
我们需要先获取 IOC 容器,才能从容器中获取到我们需要的 bean,实在是麻烦。
二、Spring 的单元测试:
在 Spring 的单元测试中我们只需要加上 @Autowired 就能自动为我们注入所需要的 bean,我们直接使用就是了。
使用步骤:
- 加入 jar 包:spring-test.4.3.7.RELEASE
在测试类上加上以下两个注解:
- @RunWith(SpringJUnit4ClassRunner.class):使用 Spring 的 JUnit
- @ContextConfiguration(locations= {“classpath:appliationContext.xml”}):指定 spring 配置文件的位置。
在所需要的 bean 上加上 @Autowired。
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 cn.edu.pzhu.cg.service.EmployeeService;
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:appliationContext.xml"})
public class ServiceTest {
@Autowired
private EmployeeService employeeService;
@Test
public void testQueryByName() {
String name = "Tom";
System.out.println(employeeService.getEmpByName(name));
}
}