如果该对象的字符串属性与预定值不匹配,我将进行测试以验证是否返回空对象。我的代码是

import guru.springframework.sfgpetclinic.model.Speciality;
import guru.springframework.sfgpetclinic.repositories.SpecialtyRepository;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.mockito.junit.jupiter.MockitoExtension;

import java.util.Optional;

import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.jupiter.api.Assertions.assertThrows;
import static org.mockito.BDDMockito.*;
import static org.junit.jupiter.api.Assertions.*;
import static org.mockito.BDDMockito.given;
import static org.mockito.BDDMockito.then;

@ExtendWith(MockitoExtension.class)
class SpecialtySDJpaServiceTest {

    @Mock
    SpecialtyRepository specialtyRepository;

    @InjectMocks
    SpecialtySDJpaService service;


    @Test
    void testSaveLambdaNoMatch() {

       // Given
       final String MATCH_ME = "MATCH_ME";
       Speciality speciality = new Speciality();
       speciality.setDescription("Not a match");

       Speciality savedSpeciality = new Speciality();
       savedSpeciality.setId(1L);

       // Need mock to only return on match MATCH_ME string
       given(specialtyRepository.save(argThat(argument -> argument.getDescription().equals(MATCH_ME)))).willReturn(savedSpeciality);

       // When
       Speciality returnedSpeciality = service.save(speciality);

       // Then
       assertNull(returnedSpeciality);

    }

   // Other tests...

}


该测试失败,并显示以下消息

org.mockito.exceptions.misusing.PotentialStubbingProblem:
Strict stubbing argument mismatch. Please check:
- this invocation of 'save' method:
specialtyRepository.save(
guru.springframework.sfgpetclinic.model.Speciality@19ae6bb


我认为问题在于argThat()使用完全匹配的方案。我想将模拟匹配设置为宽松

@Mock(lenient = true)
SpecialtyRepository specialtyRepository


但是Intellij无法识别lenient参数。我正在使用JUnit 5和Mockito 2.23.0

最佳答案

Mockito版本2.23.3中引入了@Mock(lenient = true)。

您必须升级或使用other way编写此代码:

lenient().given(specialtyRepository.save(argThat(argument -> argument.getDescription().equals(MATCH_ME)))).willReturn(savedSpeciality);

关于java - 与Mockito Mock匹配的宽松字符串,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/58244648/

10-16 16:17