首頁 > 軟體

Spring整合Junit詳解

2022-07-18 22:05:32

1,整合Junit4

maven引入spring-test 和 junit4

            <dependency>
                <groupId>org.springframework</groupId>
                <artifactId>spring-test</artifactId>
                <version>5.2.22.RELEASE</version>
            </dependency>            
            <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.13</version>
                <scope>test</scope>
            </dependency>

在test目錄下建立測試類

@RunWith(SpringJUnit4ClassRunner.class)  //啟用Junit4
@ContextConfiguration("classpath:META-INF/context-junit.xml") //載入組態檔
public class SpringJunit4 {
    @Autowired
    private Machine machine;
    @Test
    public void test1() throws Exception {
        System.out.println(machine.getObject());
    }
}

2,整合Junit5

1,maven引入spring-test 和 junit5

JUnit 5 =JUnit Platform+JUnit Jupiter+JUnit Vintage

            <!-- junit 5 -->
            <dependency>
                <groupId>org.junit.jupiter</groupId>
                <artifactId>junit-jupiter</artifactId>
                <version>5.8.2</version>
                <scope>test</scope>
            </dependency>

2,在test目錄下建立測試類

@ExtendWith(SpringExtension.class) //啟用Junit5
@ContextConfiguration("classpath:META-INF/context-junit.xml") //載入組態檔
public class SpringJunit5 {
    @Autowired
    private Machine machine;
    @Test
    public void test1() throws Exception {
        System.out.println(machine.getObject());
    }
}

說明:在spring5中,可以用複合註解 @SpringJUnitConfig(locations = {"classpath:META-INF/context-junit.xml"}) 代替@ExtendWith(SpringExtension.class) 和@ContextConfiguration("classpath:META-INF/context-junit.xml")

//@ExtendWith(SpringExtension.class) //啟用Junit5
//@ContextConfiguration("classpath:META-INF/context-junit.xml") //載入組態檔
@SpringJUnitConfig(locations = {"classpath:META-INF/context-junit.xml"})
public class SpringJunit5 {
    @Autowired
    private Machine machine;
    @Test
    public void test1() throws Exception {
        System.out.println(machine.getObject());
    }
}

到此這篇關於Spring整合Junit詳解的文章就介紹到這了,更多相關Spring Junit內容請搜尋it145.com以前的文章或繼續瀏覽下面的相關文章希望大家以後多多支援it145.com!


IT145.com E-mail:sddin#qq.com