为了账号安全,请及时绑定邮箱和手机立即绑定

与 Mockito Mock 进行宽松的字符串匹配

与 Mockito Mock 进行宽松的字符串匹配

函数式编程 2023-09-27 10:37:57
我有一个测试来验证空对象的返回(如果该对象的字符串属性与预先确定的值不匹配)。我的代码是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
查看完整描述

1 回答

?
慕神8447489

TA贡献1780条经验 获得超1个赞

@Mock(lenient = true) 是在Mockitoversion中引入的2.23.3

您必须升级或使用other way来编写以下内容:

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



查看完整回答
反对 回复 2023-09-27
  • 1 回答
  • 0 关注
  • 209 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信