IDEA中單元測試


 

Intellij IDEA中添加JUnit單元測試

 

springboot(16)Spring Boot使用單元測試

 

Spring Boot 進行測試提示 TestContextAnnotationUtils 錯誤

 

創建存放測試文件的目錄

需要在project下新建一個文件夾,用於存放自動生成的測試.java文件,比如 Factorial.java類對應的 FactorialTest.java文件的存放位置
這里我新建一個目錄,和scr目錄同級,如圖
image-20200410001446930

接下來需要將這個文件夾,設置為存放生成測試文件的目錄
打開項目設置
image-20200410001551607

image-20200410001659216

使用JUnit

當想要為當前類添加測試代碼,只需要在當前類中使用Alt+inset(或者導航欄中點擊Code-Generator)快捷鍵,選擇JUnit-JUnit4,就會自動生成當前類的測試類:

插件默認會測試所有方法,使用快捷鍵Ctrl+Shift+T可以選擇性的測試部分方法,非常的方便:

在輸出路徑中就可以看到自動生成的測試類,含有需要測試的方法,接下來就可以編寫代碼對類進行測試啦

<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency>

 

 

package com.dudu.service;
import com.dudu.domain.LearnResource;
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;
import static org.hamcrest.CoreMatchers.*;

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

    @Autowired
    private LearnService learnService;

    @Test
    public void getLearn(){
        LearnResource learnResource=learnService.selectByKey(1001L);
        Assert.assertThat(learnResource.getAuthor(),is("嘟嘟MD獨立博客"));
    }
}

 

如果運行報錯,去掉jar包的版本號:

Spring Boot 進行測試提示 TestContextAnnotationUtils 錯誤

 

Spring Boot 進行測試提示 TestContextAnnotationUtils 錯誤


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM