1. 程式人生 > >Intellij IDEA使用junit單元測試及其junit與spring版本不相容問題

Intellij IDEA使用junit單元測試及其junit與spring版本不相容問題

下面是我在建立springboot測試類中的說明和遇到的問題

建立好了測試類後

1.測試service層測試類需要加上註解:@Runwith,@SpringBootTest
2.測試Controller層測試類需要加上註解:@Runwith,@SpringBootTest,@AutoConfigureMoceMvc

例如我的service測試:

import com.oldbig.domain.Girl;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;


@RunWith(SpringRunner.class)
@SpringBootTest
public class GirlServiceTest {

    @Autowired
    private GirlService girlService;

    @Test
    public void getAge() throws Exception {
        Girl girl = girlService.getAge(5);
        Assert.assertEquals(new Integer(15),girl.getAge());
    }

}

如果測試成功的話並且資料對應的話則無異常顯示,但是我在執行時出現:

java.lang.IllegalStateException: SpringJUnit4ClassRunner requires JUnit 4.12 or higher.錯誤

表示我的junit版本太低了需要4.12以上,我換了4.12後,發現專案都執行不了(本來用4.10專案可以執行只是測試錯誤):顯示程式包org.junit不存在 錯誤

這時候我換了更高版本4.4,4.5之類的都不行,百度了以下,發現了  4.12-beta-3(烈火漢化版),新增入依賴

<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12-beta-3</version>
</dependency>
發現專案能執行,測試也能順利進行,終於解決了bug