我正在嘗試測驗以下從Price服務中獲取資料的方法。
CountryServiceImpl:
public PriceDTO findBCountryUuid(UUID countryUuid) {
// code omitted
// !!! currency value is null
Currency currency = currencyService.getCurrencyByCountry(countryUuid);
return new PriceDTO(currency);
}
這是PriceService.
價格服務實施:
@Override
public Currency getCurrencyByCountry(UUID countryUuid) {
return countryRepository.findByUuid(countryUuid)
.orElseThrow(() -> new EntityNotFoundException("Country"))
.getCurrency();
}
我使用以下方法進行測驗:
@Mock
private CountryRepository countryRepository;
@Mock
private CurrencyServiceImpl currencyService;
@InjectMocks
private CountryServiceImpl priceService;
@Test
public void test_findBCountryUuid() {
// code omitted
final Country country = new Country();
country.setName("Country");
country.setCurrency(currency);
when(countryRepository.findByUuid(countryUuid))
.thenReturn(Optional.of(country));
PriceDTO result = priceService.findBCountryUuid(countryUuid);
//... assertions
}
問題是;在該findBCountryUuid方法中,該currency值為空,因此我在result我的 tets 方法的引數中獲得了空價格值。該問題完全與使用與PriceService. 我想我應該嘲笑PriceService使用而不是嘲笑的回購PriceService。這個實作有什么問題?
uj5u.com熱心網友回復:
您需要模擬該方法的行為 PriceServiceImpl.getCurrencyByCountry
PriceServiceImpl priceServiceMock = Mockito.mock(PriceServiceImpl.class);
Mockito.when(priceServiceMock.getCurrencyByCountry(any(UUID.class))).thenReturn(new Currency()); // Return either a newly instantiated object or a mockek one based on your need
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/404714.html
標籤:
