Search code examples
javarestjunitintegration-testing

How to test a Spring REST consumer with JUnit


I'm creating a Java Spring based microservice application that communicates using REST endpoints.

The app itself is so far has a simple structure: UI <-> DBLayer. The UI module is a api consumer and DBLayer is an api provider.

That being said I would like to test if my UI makes the correct REST calls using JUnit and/or Mockito. To be more specific, say I have a service class like this:

@Service
public class AuthorityService {

    @Autowired
    private RestTemplate restTemplate;

    public Authority getAuthority(String authorityName) {
        Authority authority = 
               restTemplate.getForObject(
                  "http://localhost:8080/authorities/" + authorityName,
                   Authority.class);           
        return authority;
    }
}

In order to test this service method I would like to somehow verify that exactly this endpoint was called. Is there a way to wrap the service method and somehow assert a rest GET/POST/PUT etc. calls being made?

The desired test class should look something like this:

public class AuthorityServiceTest {
    private AuthorityService authorityService = new AuthorityService();

    @Test
    public void getAuthorityTest(){
        Assert.assertHttpGETCallMade(
                authorityService.getAuthority("test"),
                "http://localhost:8080/authorities/test");
    }
}

Solution

  • You can use Mockito to inject the template, then verify the call.

    @ExtendWith(MockitoExtension.class) // RunWith(MockitoJUnitRunner.class) for JUnit 4
    public class AuthorityServiceTest {
        @InjectMocks
        private AuthorityService sut;
    
        @Mock RestTemplate restTemplate;
    
        @Test
        public void getAuthorityTest(){
            // mock rest call
            Authority auth = mock(Authority.class);
            when(restTemplate.getForObject(any(String.class), any(Class.class)).thenReturn(auth);
    
            Authority result = sut.getAuthority("test");
    
            // verify mock result was returned
            assertSame(auth, result);
            // verify call to rest template was performed
            verify(restTemplate).getForObject(
                  "http://localhost:8080/authorities/test",
                   Authority.class);
        }
    }