Mockito の概要
モック オブジェクトのメソッドを呼び出すと、実際のメソッドは実行されませんが、戻り値の型のデフォルト値 (object は null を返し、int は 0 を返します)。それ以外の場合は、 when (Method).thenReturn(value) を指定してメソッドの戻り値を指定します。同時に、モック オブジェクトを追跡し、verify メソッドを使用してそれが呼び出されたかどうかを確認できます。スパイ オブジェクトはデフォルトで実際のメソッドを実行し、戻り値は when.thenReturn を通じてオーバーライドできます。モックが一部のメソッドの実行を回避し、指定された値を直接返す限り、他のテストには便利であることがわかります。
サービス テスト ケース
必要な依存関係
<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); } }
コントローラー テスト ケース
必要な依存関係
<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 中国語 Web サイトの他の関連記事を参照してください。
声明
この記事は亿速云で複製されています。侵害がある場合は、admin@php.cn までご連絡ください。

ホットAIツール

Undresser.AI Undress
リアルなヌード写真を作成する AI 搭載アプリ

AI Clothes Remover
写真から衣服を削除するオンライン AI ツール。

Undress AI Tool
脱衣画像を無料で

Clothoff.io
AI衣類リムーバー

AI Hentai Generator
AIヘンタイを無料で生成します。

人気の記事
R.E.P.O.説明されたエネルギー結晶と彼らが何をするか(黄色のクリスタル)
1 か月前By尊渡假赌尊渡假赌尊渡假赌
R.E.P.O.最高のグラフィック設定
1 か月前By尊渡假赌尊渡假赌尊渡假赌
アサシンのクリードシャドウズ:シーシェルリドルソリューション
3週間前ByDDD
Will R.E.P.O.クロスプレイがありますか?
1 か月前By尊渡假赌尊渡假赌尊渡假赌

ホットツール

WebStorm Mac版
便利なJavaScript開発ツール

SublimeText3 Linux 新バージョン
SublimeText3 Linux 最新バージョン

AtomエディタMac版ダウンロード
最も人気のあるオープンソースエディター

SublimeText3 英語版
推奨: Win バージョン、コードプロンプトをサポート!

SAP NetWeaver Server Adapter for Eclipse
Eclipse を SAP NetWeaver アプリケーション サーバーと統合します。
