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

我有一个测试来验证空对象的返回(如果该对象的字符串属性与预先确定的值不匹配)。我的代码是


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


函数式编程
浏览 210回答 1
1回答

慕神8447489

@Mock(lenient = true) 是在Mockitoversion中引入的2.23.3。您必须升级或使用other way来编写以下内容:lenient().when(specialtyRepository.save(argThat(argument -> argument.getDescription().equals(MATCH_ME)))).willReturn(savedSpeciality);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java