Maison >Java >javaDidacticiel >Méthode thenReturn() dans l'exemple Mockito

Méthode thenReturn() dans l'exemple Mockito

Mary-Kate Olsen
Mary-Kate Olsenoriginal
2025-01-27 00:07:07995parcourir

thenReturn() method in Mockito example

Scénario: se moquer d'un service pour tester un contrôleur

  1. Code d'application Employé.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;
    }
}

EmployingService.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. Code de test unitaire à l'aide de thereTurn () 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");
    }
}

Explication
quand (). thereraturn ():

se moque du comportement de EmployingService.geTemployeeById ("1") pour retourner un objet employé spécifique lorsqu'il est appelé avec "1".
Injection de dépendance:

@mock crée une maquette de la restauration d'employés.

@InjectMocks injecte le Mock EmployerService dans l'employeeController.

Vérifier:
Vérifiez (Employés Service, Times (1)). GetEmployeeById ("1") garantit que la méthode moquée a été appelée exactement une fois.

Affirmation:
Valide l'objet de l'employé retourné contre les valeurs attendues.

sortie
Lorsque le test est exécuté:

Il appellera la méthode du contrôleur.

Le service moqué renverra l'objet de l'employé tronqué.
Le test passera si:
L'objet employé retourné correspond aux valeurs attendues.

La méthode de service moquée était appelée le nombre attendu de fois.

Il s'agit d'un moyen propre et pratique d'utiliser thereTrUnturn () dans une application de démarrage de printemps pour tester la logique du contrôleur sans s'appuyer sur l'implémentation réelle du service.

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn