2018年4月28日 星期六

JUnit 5 整合 Spring 5


<properties>
    <junit.platform.version>1.1.1</junit.platform.version>
    <junit.version>5.1.1</junit.version>
    <spring.version>5.0.5.RELEASE</spring.version>
</properties>
    
<dependencies>
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-api</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>${junit.version}</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-launcher</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>
    
    <dependency>
        <groupId>org.junit.platform</groupId>
        <artifactId>junit-platform-engine</artifactId>
        <version>${junit.platform.version}</version>
        <scope>test</scope>
    </dependency>
    
    
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>${spring.version}</version>
    </dependency>
    
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-test</artifactId>
        <version>${spring.version}</version>
        <scope>test</scope>
    </dependency>
</dependencies>

※如果要用 spring-web ,必需多個 spring-web 時;如果要用 spring mvc,必需多個 spring-webmvc


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.junit.jupiter.SpringExtension;
import org.springframework.test.context.junit.jupiter.SpringJUnitConfig;
import lt.SpringMaven.bean.Animal;
import lt.SpringMaven.bean.Bird;
import lt.SpringMaven.bean.Chicken;
    
@ExtendWith(SpringExtension.class)
// @SpringJUnitConfig(Animal.class)
@SpringJUnitConfig(locations = "classpath:applicationContext.xml")
public class AppTest {
    @Autowired(required = false)
    private Animal animal;
    
    @Autowired(required = false)
    private Bird bird;
    
    @Autowired(required = false)
    private Chicken chicken;
    
    @Test
    public void testBruce() {
        System.out.println("animal=" + animal);
        System.out.println("bird=" + bird);
        System.out.println("chicken=" + chicken);
    }
}

※@SpringJUnitConfig 可以寫設定檔或 annotation,其實裡面呼叫的還是 2.5 的 @ContextConfiguration,所以也可以使用這個 annotation

※如果是 web,要使用 @SpringJUnitWebConfig



沒有留言:

張貼留言