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個注解):