Search code examples
javaspringspring-bootservicespring-test

Java Spring Boot: testing service


I'm having issues testing a service because I can't seem to be able to mock the service response with a RestTemplate.

Here's the service code:

@Service
public class PricingServiceImpl implements PricingService {
    private static final String URL = "http://127.0.0.1:4000/pricing?countryCode=";
    @Autowired
    RestTemplate restTemplate;

    @Override
    public ResponseEntity<BigDecimal> getPricing(String countryCode) {
        return restTemplate.exchange(URL + countryCode, HttpMethod.GET, null, new ParameterizedTypeReference<BigDecimal>() {
        });
    }
}

Here's the test code:

@ExtendWith(MockitoExtension.class)
@RunWith(SpringRunner.class)
public class PricingServiceImplTest {
    @InjectMocks
    private PricingService pricingService = new PricingServiceImpl();
    @Mock
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        PricingResponse pricingResponse = new PricingResponse();
        pricingResponse.setPrice(BigDecimal.TEN);
        Mockito.when(restTemplate.exchange(any(), eq(HttpMethod.GET), any(), any(ParameterizedTypeReference.class))).thenReturn(new ResponseEntity<>(pricingResponse, HttpStatus.OK));
    }

    @Test
    public void test() {
        ResponseEntity<BigDecimal> result = pricingService.getPricing("NL");
        Assertions.assertNotNull(result);
    }
}

I'm simply trying to assert that result isn't null so I can make sure I'm doing something correct, but it's not working, as the result is always null.

Edit

I've modified the test class to use a setter for the RestTemplate but still the service is returning null:

@RunWith(MockitoJUnitRunner.class)
public class PricingServiceImplTest {
    private PricingServiceImpl pricingService = new PricingServiceImpl();
    @Mock
    private RestTemplate restTemplate;

    @Before
    public void setUp() {
        PricingResponse pricingResponse = new PricingResponse();
        pricingResponse.setPrice(BigDecimal.TEN);
        Mockito.when(restTemplate.exchange(any(), eq(HttpMethod.GET), any(), any(ParameterizedTypeReference.class))).thenReturn(new ResponseEntity<>(pricingResponse, HttpStatus.OK));
    }

    @Test
    public void test() {
        pricingService.setRestTemplate(restTemplate);
        ResponseEntity<BigDecimal> result = pricingService.getPricing("NL");
        Assertions.assertNotNull(result);
    }
}

Solution

  • Try the following approach

    pricingService.setRestTemplate(restTemplate);
    

    It looks like you are trying to mock the RestTemplate object in your test, but the PricingServiceImpl is still using the real RestTemplate object that is autowired in the class.