单元测试:无法从 Java 中的服务获取价值

Unit Test: Cannot get value from Service in Java

我正在尝试测试以下从 Price 服务获取数据的方法。

CountryServiceImpl:

public PriceDTO findBCountryUuid(UUID countryUuid) {
        
        // code omitted

    // !!! currency value is null
        Currency currency = currencyService.getCurrencyByCountry(countryUuid);
        
        return new PriceDTO(currency);
}

这里是 PriceService.

PriceServiceImpl:

@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 值为空,因此我在 tets 方法的 result 参数中得到空价格值。 该问题完全与使用与 PriceService 相关的错误模拟或注释有关。我想我应该模拟 PriceService 使用的 repo 而不是模拟 PriceService。这个实现有什么问题?

您需要模拟方法的行为 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