0

I am writing a simple REST client, my service class has one method using

RestTemplate.getForObject()

I would like to practice testing but I don't really know if we should test the class. I also do not know how to test method that does not do much. Should I write any unit tests?

AS Mackay
  • 2,831
  • 9
  • 19
  • 25
  • You should write the test against your own code, and mock out the rest template instance. That way you can test out that your surrounding support code handles the response(s) from the restTemplate call. (For example, if you have special handling for a 404/not found response.) – Roddy of the Frozen Peas May 15 '19 at 18:56
  • Related: [How to mock RestTemplate with MockRestServiceServer](https://stackoverflow.com/questions/42409768/how-to-mock-resttemplate-with-mockrestserviceserver). Additionally: [mock resttemplate to test a service as restFul client](https://stackoverflow.com/questions/38183439/mock-resttemplate-to-test-a-service-as-restful-client/38191345). And finally: [mock rest template for unit test](https://stackoverflow.com/questions/55016886/mock-rest-template-for-unit-test) – g00glen00b May 16 '19 at 07:24

1 Answers1

0

You can test, that request has been sent. For example you have the next service:

@Service
public void QueryService {

    private final RestTemplate restTemplate;

    @Autowired
    public QueryService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    public List<Employee> void makeQuery() {
        ResponseEntity<List<Employee>> response = restTemplate.getForObject(
            "http://localhost:8080/employees",
            EmployeeList.class);
        return response.getEmployees();
    }
}

For the method makeQuery you can write the next unit test:

@RunWith(MockitoJUnitRunner.class)
public class QueryServiceTest {

    @Mock
    private RestTemplate restTemplate;

    @InjectMocks
    private QueryService queryService;

    @Test
    public void testMakeQueryRequestHasBeenSent() {
        List<Employee> result = queryService.makeQuery();

        // This string checks that method getForObject has been invoked
        verify(restTemplate).getForObject(anyString(), any(Class.class));
    }
}

In the future, if you will change makeQuery method and forget to send request using restTemplate, this test will fail.

Golov Pavel
  • 624
  • 5
  • 15
  • I tried your solution but method queryService.makeQuery() in test class throws NPE even tho it works fine in service class. Any idea what am i doing wrong? – someone_smarter May 15 '19 at 16:19
  • It may happend because you don't mock `queryService` properly. I created [simple project](https://github.com/GolovPavel/rest-template-unit-test) for you, which works perfectly and doesn't fall by NPE. – Golov Pavel May 15 '19 at 18:52