整合Junit4
第一步:引入Spring相关针对测试依赖
spring-test-5.2.6.RELEASE.jar
hamcrest-core-1.3.jar
junit-4.13.1.jar
第二步:创建测试类,使用注解方式完成:
@Test 使用 import org.junit.Test;
import com.spring5.service.TransferService;
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;
@RunWith(SpringJUnit4ClassRunner.class) //单元测试框架 SpringJUnit4ClassRunner @ContextConfiguration在spring-test包
@ContextConfiguration("classpath:bean1.xml")//加载配置文件
public class Junit4Test {
@Autowired
private TransferService transferService;
@Test
public void test1(){
transferService.transfer();
}
}
整合Junit5
第一步:引入Junit5的jar包
第二步:创建测试类,使用注解方式完成
@Test 使用 org.junit.jupiter.api.Test;
import com.spring5.service.TransferService;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit.jupiter.SpringExtension;
@ExtendWith(SpringExtension.class)
@ContextConfiguration("classpath:bean1.xml")
public class Junit5Test {
@Autowired
private TransferService transferService;
@Test
public void test1(){
transferService.transfer();
}
}
使用复合注解,代替上面两个注解
import com.spring5.service.TransferService;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
//@ExtendWith(SpringExtension.class)
//@ContextConfiguration("classpath:bean1.xml")
@SpringJUnitConfig(locations = "classpath:bean1.xml")
public class Junit5Test {
@Autowired
private TransferService transferService;
@Test
public void test1(){
transferService.transfer();
}
}