Home > Software design >  Unit Test: Cannot get value from Service in Java
Unit Test: Cannot get value from Service in Java

Time:01-06

I am trying to test the following method that gets data from Price service.

CountryServiceImpl:

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

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

Here is the PriceService.

PriceServiceImpl:

@Override
public Currency getCurrencyByCountry(UUID countryUuid) {
        return countryRepository.findByUuid(countryUuid)
                        .orElseThrow(() -> new EntityNotFoundException("Country"))
                        .getCurrency();
}

I use the following approach to test:

@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        
}

The problem is that; In the findBCountryUuid method, the currency value is null, and for this reason I get null price value in the result parameter of my tets method. The problem is completely related to using wrong mocking or annotation related to the PriceService. I think I should mock the repo that PriceService uses instead of mocking PriceService. What is wrong with this implementation?

CodePudding user response:

You need to mock the behaviour for the method 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
  •  Tags:  
  • Related