一、快速使用
1.导入依赖
junit
spring-test
2.测试类上加注解
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations= {"classpath:配置文件位置"})
3.注入测试对象
@Autowired
4.测试方法上加注解
@Test
二、原理详解
junit无法为我们创建spring容器,所以每个测试方法都需要手动获取容器。
例如
package com.yooyo.test;
import java.util.List;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.yooyo.domain.Account;
import com.yooyo.service.AccountService;
public class AccoutTest {
@Test
public void run1() {
/**
*获取容器并获取对象,重复代码
**/
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
AccountService accountService = ac.getBean(AccountService.class);
List<Account> list = accountService.findAll();
System.out.println(list);
}
@Test
public void run2() {
/**
*获取容器并获取对象,重复代码
**/
ApplicationContext ac=new ClassPathXmlApplicationContext("classpath:spring/applicationContext.xml");
AccountService accountService = ac.getBean(AccountService.class);
List<Account> list = accountService.findAll();
System.out.println(list);
}
}
但是junit暴露了一个注解@RunWith(SpringJUnit4ClassRunner.class),可以使用它使用spring提供的运行器替换掉junit的运行器。这样我们就可以在测试类中直接使用@Autowired注入对象使用了。
例如
package com.yooyo.test;
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.yooyo.service.AccountService;
//1.替换junit的运行器为spring的运行器,该注解为junit提供
@RunWith(SpringJUnit4ClassRunner.class)
//2.替换掉运行器以后,测试类可以为我们创建spring容器了,但是需要知道配置文件的位置,加载配置文件或注解类
@ContextConfiguration(locations= {"classpath:spring/applicationContext.xml"})
public class AccoutTest {
@Autowired
private AccountService accountService;
@Test
public void run1() {
System.out.println(accountService.findAll());
}
@Test
public void run2() {
System.out.println(accountService.findAll());
}
}