There is a client-server application.

For testing the server, I used an in-memory database, but with testing the client, I had problems.

It connects to the server using RestTemplate , therefore, I can only test the client when the server is running, and this is probably not entirely correct. And then, the client is tested in my case on a working database, and not on in-memory, this is definitely not good.

How should I test the client side?

Here, for example, I have a method in the client's Service Layer:

 public class WebAppDepartmentsService { private final String HOST_URL = "http://localhost:8080/server/departments"; @Override public void delete(String departmentName){ RestTemplate restTemplate = new RestTemplate(); String uri = "/remove/department/{departmentName}"; Map<String, String> map = new HashMap<>(); map.put("departmentName", departmentName); restTemplate.postForLocation(HOST_URL + uri, Department.class, map); } } 

And now it is tested like this:

 public class WebAppDepartmentsServiceTest { @Test public void testDelete(){ departmentService = new WebAppDepartmentsService(); departmentService.delete("QA"); List<Department> departments = departmentService.getAll(); assertEquals(5, departments.size()); } } 

PS If possible, I would like a specific test example for the delete(); method I presented delete();

    1 answer 1

    When writing unit tests on the client, it is unnecessary to keep the server running - it is enough just to run the server before running the tests, and after executing the query, check that the necessary queries have been executed. But for this, it will be necessary to rework the client’s methods a bit, namely, not to create the RestTemplate hand. Instead, you can inject it as a dependency through @Autowired :

     @Service public class WebAppDepartmentsServiceImpl implements WebAppDepartmentsService { private final RestTemplate restTemplate; public WebAppDepartmentsServiceImpl(@Autowired RestTemplate restTemplate) { this.restTemplate = restTemplate; } ... } 

    After that, in the test class, create a server for your RestTemplate :

     public class WebAppDepartmentsServiceTest { private RestTemplate restTemplate = new RestTemplate(); private WebAppDepartmentsService departmentService = new WebAppDepartmentsServiceImpl(restTemplate); private MockRestServiceServer mockServer; @Before public void setUp() { mockServer = MockRestServiceServer.createServer(restTemplate); } @Test public void testDelete() { // given mockServer .expect(requestTo("/remove/department/QA")) .andExpect(method(HttpMethod.POST)) .andRespond(withSuccess( "{\"id\" : \"42\"}", MediaType.APPLICATION_JSON)); // when departmentService.delete("QA"); // then mockServer.verify(); } ... }