簡體   English   中英

為什么 lenient 解決了給定示例中的不必要的 Stubbing 異常

[英]Why lenient solves Unneccessary Stubbing exception in given example

我已經閱讀過以前的問題,但沒有直接指出我的問題的確切答案。 我的代碼如下:

@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);

 }
}

我的測試 class 如下:

@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); 或 lenient 的注釋效果很好。 但背后的邏輯是什么。

為什么 lenient 在給定的例子中解決了不必要的 Stubbing 異常?

看起來您的cityMapper從未被使用過,這就是您看到異常的原因。

findById方法中用cityMapper替換CityMapper.INSTANCE並且UnnecessaryStubbingException應該 go 消失。 但是,如果您的代碼仍然執行它應該執行的操作,我無法根據我所看到的情況做出決定。

真正的依賴是CityMapper cityMapper。 在 findById_Success 你打電話

cityMapper.cityToCityDto(city)

但是,如果您看到真正的方法並沒有調用它。 反而

CityMapper.INSTANCE.cityToCityDto(city)

已經用過。 改變其中任何一個,它應該工作

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM