12-spring整合junit
12.1 基于完全xml版本整合
12.1.1 创建项目
12.1.2 配置pom.xml
<junit.version>4.12</junit.version>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>${junit.version}</version>
</dependency>
12.1.3 编写测试类
package cn.guardwhy.junit;
import cn.guardwhy.domain.Customer;
import cn.guardwhy.service.CustomerService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import java.util.List;
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(value = {
"classpath:bean.xml"})
public class SpringJunit {
@Test
public void findAllCustomersTest1(){
ApplicationContext context = new ClassPathXmlApplicationContext("classpath:bean.xml");
CustomerService customerService = (CustomerService) context.getBean("customerService");
List<Customer> list = customerService.findAllCustomers();
for(Customer c:list){
System.out.println(c);
}
}
@Autowired
private CustomerService customerService;
@Test
public void findAllCustomersTest2(){
List<Customer> list = customerService.findAllCustomers();
for(Customer c:list){
System.out.println(c);
}
}
}
12.1.4 执行结果
12.2 基于完全注解版本整合
12.2.1 项目目录
12.2.2 编写测试类
package cn.guardwhy.junit;
import cn.guardwhy.config.SpringConfiguration;
import cn.guardwhy.domain.Customer;
import cn.guardwhy.service.CustomerService;
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 java.util.List;
@RunWith(value = SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = {
SpringConfiguration.class})
public class SpringJunit {
@Autowired
private CustomerService customerService;
@Test
public void findAllCustomersTest2(){
List<Customer> list = customerService.findAllCustomers();
for(Customer c:list){
System.out.println(c);
}
}
}