Mockito簡介
呼叫mock物件的方法時,不會執行真實的方法,而是傳回類型的預設值,如object回傳null, int回傳0等,否則透過指定when (方法).thenReturn(value)來指定方法的回傳值。同時mock物件可以進行追蹤,使用verify方法看是否已經被呼叫過。而spy對象,預設會執行真實方法,返回值可以透過when.thenReturn進行覆寫。可見mock只要避開了執行一些方法,直接回傳指定的值,方便做其他測試。
Service測試案例
需要的依賴
<dependency> <groupid>junit</groupid> <artifactid>junit</artifactid> <version>4.12</version> <scope>test</scope> </dependency> <dependency> <groupid>org.mockito</groupid> <artifactid>mockito-core</artifactid> <version>2.23.4</version> <scope>test</scope> </dependency> <dependency> <groupid>org.springframework.boot</groupid> <artifactid>spring-boot-test</artifactid> <version>2.1.13.RELEASE</version> </dependency>
程式碼範例
@RunWith(MockitoJUnitRunner.class) @SpringBootTest() public class StudentServiceTest { @InjectMocks StudentService studentService = new StudentServiceImpl(); @Mock StudentDAO studentDAO; @Before public void before(){ Mockito.doReturn(new StudentDO("张三", 18)).when(studentDAO).read(Mockito.anyString()); } @Test public void testRead(){ StudentDO read = studentService.read(""); Assert.assertNotNull(read); } }
Controller測試案例
需要的依賴
<dependency> <groupid>org.springframework</groupid> <artifactid>spring-test</artifactid> <version>5.1.14.RELEASE</version> </dependency> <dependency> <groupid>com.jayway.jsonpath</groupid> <artifactid>json-path</artifactid> <version>2.4.0</version> </dependency>
程式碼範例
@RunWith(MockitoJUnitRunner.class) @SpringBootTest() public class StudentControllerTest { @Resource MockMvc mockMvc; @InjectMocks StudentController studentController; @Mock StudentService studentService; @Before public void before() { mockMvc = MockMvcBuilders.standaloneSetup(studentController).build(); Mockito.doReturn(new StudentDO("张三", 18)).when(studentService).read(Mockito.anyString()); } @Test public void testRead() throws Exception { MockHttpServletRequestBuilder request = MockMvcRequestBuilders.get("/student/read/1"); mockMvc.perform(request) .andDo(print()) .andExpect(status().isOk()) .andExpect(jsonPath("$.name").value("张三")); } }
以上是Java單元測試Mockito如何用的詳細內容。更多資訊請關注PHP中文網其他相關文章!
陳述
本文轉載於:亿速云。如有侵權,請聯絡admin@php.cn刪除

熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 個月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最佳圖形設置
1 個月前By尊渡假赌尊渡假赌尊渡假赌
刺客信條陰影:貝殼謎語解決方案
3 週前ByDDD
Windows 11 KB5054979中的新功能以及如何解決更新問題
2 週前ByDDD
威爾R.E.P.O.有交叉遊戲嗎?
1 個月前By尊渡假赌尊渡假赌尊渡假赌

熱工具

MinGW - Minimalist GNU for Windows
這個專案正在遷移到osdn.net/projects/mingw的過程中,你可以繼續在那裡關注我們。 MinGW:GNU編譯器集合(GCC)的本機Windows移植版本,可自由分發的導入函式庫和用於建置本機Windows應用程式的頭檔;包括對MSVC執行時間的擴展,以支援C99功能。 MinGW的所有軟體都可以在64位元Windows平台上運作。

記事本++7.3.1
好用且免費的程式碼編輯器

WebStorm Mac版
好用的JavaScript開發工具

Dreamweaver Mac版
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)