1. 程式人生 > 其它 >IDEA中單元測試

IDEA中單元測試

Intellij IDEA中新增JUnit單元測試

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

建立存放測試檔案的目錄

需要在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獨立部落格")); } }