Intellij IDEA中添加JUnit單元測試
springboot(16)Spring Boot使用單元測試
Spring Boot 進行測試提示 TestContextAnnotationUtils 錯誤
創建存放測試文件的目錄
需要在project下新建一個文件夾,用於存放自動生成的測試.java文件,比如 Factorial.java
類對應的 FactorialTest.java
文件的存放位置
這里我新建一個目錄,和scr目錄同級,如圖
接下來需要將這個文件夾,設置為存放生成測試文件的目錄
打開項目設置
使用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 錯誤