ホームページ > Java > &#&チュートリアル > Mockito の例の thenReturn() メソッド

Mockito の例の thenReturn() メソッド

Mary-Kate Olsen
リリース: 2025-01-27 00:07:07
オリジナル
953 人が閲覧しました

thenReturn() method in Mockito example

シナリオ:コントローラーをテストするためにサービスをock笑する

  1. アプリケーションコード 従業員。Java
package com.example.demo.model;

public class Employee {
    private String id;
    private String name;

    // Constructors, Getters, and Setters
    public Employee(String id, String name) {
        this.id = id;
        this.name = name;
    }

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }
}

ログイン後にコピー

employeService.java

package com.example.demo.service;

import com.example.demo.model.Employee;
import org.springframework.stereotype.Service;

@Service
public class EmployeeService {
    public Employee getEmployeeById(String id) {
        // Simulate fetching employee from a database
        return new Employee(id, "Default Name");
    }
}

ログイン後にコピー

employeecontroller.java

package com.example.demo.controller;

import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class EmployeeController {
    private final EmployeeService employeeService;

    public EmployeeController(EmployeeService employeeService) {
        this.employeeService = employeeService;
    }

    @GetMapping("/employees/{id}")
    public Employee getEmployee(@PathVariable String id) {
        return employeeService.getEmployeeById(id);
    }
}

ログイン後にコピー
  1. sonreturn()を使用したユニットテストコード employeecontrollertest.java
package com.example.demo.controller;

import com.example.demo.model.Employee;
import com.example.demo.service.EmployeeService;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import static org.mockito.Mockito.*;
import static org.junit.jupiter.api.Assertions.*;

class EmployeeControllerTest {

    @Mock
    private EmployeeService employeeService;

    @InjectMocks
    private EmployeeController employeeController;

    public EmployeeControllerTest() {
        MockitoAnnotations.openMocks(this); // Initialize mocks
    }

    @Test
    void testGetEmployee() {
        // Arrange: Use when().thenReturn() to mock service behavior
        when(employeeService.getEmployeeById("1")).thenReturn(new Employee("1", "John Doe"));

        // Act: Call the controller method
        Employee employee = employeeController.getEmployee("1");

        // Assert: Verify the returned object
        assertNotNull(employee);
        assertEquals("1", employee.getId());
        assertEquals("John Doe", employee.getName());

        // Verify the mocked service was called
        verify(employeeService, times(1)).getEmployeeById("1");
    }
}

ログイン後にコピー

説明
when()。thenreturn():

employeeRervice.getEmployeEByID( "1")の動作をmocksして、「1」で呼び出されたときに特定の従業員オブジェクトを返すようにします。 依存関係注射:

@mockは、従業員サービスの模擬を作成します

@InjectMocksは、employeeControllerに模擬従業員サービスを注入します

検証:

Verify(employeService、times(1))。getemployeebyid( "1")モックされたメソッドが正確に1回呼び出されたことを確認します。

アサーション:

返された従業員オブジェクトを期待値に対して検証します
output

テストが実行されたとき:


コントローラーメソッドを呼び出します

ockedされたサービスは、スタブの従業員オブジェクトを返します。

テストは以下の場合に渡されます 返された従業員オブジェクトは、期待値と一致します
ockedされたサービス方法は、予想される回数と呼ばれていました。

これは、実際のサービスの実装に依存せずに、スプリングブートアプリケーションでSpring Bootアプリケーションで使用するためのクリーンで実用的な方法です。

以上がMockito の例の thenReturn() メソッドの詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

このウェブサイトの声明
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。
著者別の最新記事
人気のチュートリアル
詳細>
最新のダウンロード
詳細>
ウェブエフェクト
公式サイト
サイト素材
フロントエンドテンプレート