junit 为什么在给定的例子中宽松地解决不必要的存根异常

weylhg0b  于 2022-12-13  发布在  其他
关注(0)|答案(2)|浏览(141)

我已经阅读了以前的问题,但没有确切的答案直接指向我的问题。我的代码如下:

@Service
@RequiredArgsConstructor
public class CityServiceImpl implements CityService {
    private final CityRepository cityRepo;
    private final CityMapper cityMapper;
@Override
public CityDto findById(Integer id) {
    City city = cityRepo.findById(id)
            .orElseThrow(() -> new NotFoundException(NotFoundException.Domain.CITY));
    return CityMapper.INSTANCE.cityToCityDto(city);

 }
}

我的测试类如下:

@ExtendWith(MockitoExtension.class)
public class CityServiceTest {
  @Mock
  CityRepository cityRepository;

  @Mock
  CityMapper cityMapper;

  @InjectMocks
  CityServiceImpl cityService;
  City city;

  @BeforeEach
  public void init() {
    city = new City();
  }
  @Test
  void findById_Success() {
    Integer given = 1;

    CityDto expected = new CityDto();

    when(cityRepository.findById(1)).thenReturn(Optional.of(city));
    when(cityMapper.cityToCityDto(city)).thenReturn(expected);

    CityDto actual = cityService.findById(given);

    assertEquals(expected, actual);

  }
}

指向此行时出错

when(cityMapper.cityToCityDto(city)).thenReturn(expected);

检测到不必要的存根。干净且可维护的测试代码不需要不必要的代码。以下存根是不必要的

我得到一个问题,当我使用lenient.when(cityMapper.cityToCityDto(city)).thenReturn(expected);或宽松的注解工作正常。但它背后的逻辑是什么?
为什么在给定的例子中宽松地解决不必要的存根异常?

dsekswqp

dsekswqp1#

看起来您的模拟cityMapper从未被使用过,这就是您看到异常的原因。
findById方法中用cityMapper替换CityMapper.INSTANCEUnnecessaryStubbingException应该消失了。但是,如果您的代码仍然做它应该做的事情,我不能从我看到的来决定。

lh80um4z

lh80um4z2#

真实的的依赖项是CityMapper cityMapper。

cityMapper.cityToCityDto(city)

但是,如果你看到真实的的方法不是调用那个。而是

CityMapper.INSTANCE.cityToCityDto(city)

已使用。更改其中任何一个,它都应该工作

相关问题