Spring5整合JUnit4:
Book.java
package test.entity;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
@Component
public class Book {
@Value("1")
private int id;
@Value("李四")
private String name;
public Book(int id, String name) {
this.id = id;
this.name = name;
}
@Override
public String toString() {
return "Book{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
public Book() {
}
}
bean3.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!--开启组件扫描-->
<context:component-scan base-package="test"></context:component-scan>
</beans>
TestJunit4.java:
package test;
import cn.imu.service.UserService;
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 test.entity.Book;
@RunWith(SpringJUnit4ClassRunner.class)//单元测试框架,整合JUnit4
@ContextConfiguration("classpath:bean3.xml")//加载配置文件
public class TestJunit4 {
@Autowired
private Book book;
@Test
public void test(){
System.out.println(book);
}
}
运行结果:
这里的:
相当于:
极大的简化了测试代码,提高了测试效率。
Spring5整合JUnit5:
TestJunit5.java:
package test;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
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.junit.jupiter.SpringExtension;
import test.entity.Book;
@ExtendWith(SpringExtension.class)//单元测试框架,整合JUnit5
@ContextConfiguration("classpath:bean3.xml")//加载配置文件
class TestJunit5 {
@Autowired
private Book book;
@Test
public void test() {
System.out.println(book);
}
@Test
public void test1(){
ApplicationContext context=new ClassPathXmlApplicationContext("bean3.xml");
Book book=context.getBean("book",Book.class);
System.out.println(book);
}
}
运行测试test函数的结果:
整合Junit4与Junit5的不同之处:
Junit4:
Junit5:
可将2步注解简化为(即使用复合注解整合上述2个注解):