1
@MockBean
private RestTemplateBuilder restTemplateBuilder;

@MockBean
private RestTemplate restTemplate;

@InjectMocks
private FetchCoreVersionsList fetchCoreVersionsList;

 @Test
public void testCoreVersionsJsonHandle() throws Exception{
    when(restTemplate.getForObject("https://openmrs.jfrog.io/openmrs/api/storage/public/org/openmrs/api/openmrs-api/",
            String.class))
            .thenReturn(new ObjectMapper().readValue(getFileAsString("core-versions.json"), String.class));

}

On running the test , I get the following error

org.mockito.exceptions.misusing.UnfinishedStubbingException: 

Unfinished stubbing detected here: -> at org.openmrs.addonindex.scheduled.FetchCoreVersionsListIT.testCoreVersionsJsonHandle(FetchCoreVersionsListIT.java:66)

I am pretty new to creating test cases so kindly bear with me if its something silly :)

Reuben_v1
  • 714
  • 2
  • 7
  • 20
  • What is the expected return type of `getForObject()` and what does `readValue()` return? And did you do some research - I see many questions for that exception ... like https://stackoverflow.com/questions/15554119/mockito-unfinishedstubbingexception – GhostCat Jul 13 '17 at 07:07

1 Answers1

1

Here's how to do it with Spring Boot 2.0:

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;

@SpringBootTest @RunWith(SpringRunner.class)
public class myTests() {

    @MockBean RestTemplate restTemplate;

    @Test
    public void test1() {
        String uri = "http://example.org", msg="hello";
        Mockito.doReturn(msg).when(restTemplate).getForObject(eq(uri),any());
        String response = restTemplate.getForObject(uri,String.class);
        Mockito.verify(restTemplate).getForObject(eq(uri),any());
        assertEquals(response,msg);
    }

}

Mockito offers two different syntaxes: Mockito - difference between doReturn() and when()

Mockito.doReturn(new ResponseEntity<String>("200 OK",HttpStatus.OK)).when(restTemplate).postForEntity(eq(url),any(),eq(String.class));
// or
Mockito.when(restTemplate.postForEntity(eq(url), any(), eq(String.class))).thenReturn(new ResponseEntity<String>("200 OK", HttpStatus.OK));

There are other tricks, such as using eq(String.class) instead of just String.class. The error output attempts to walk you through this to degree.

Brent Bradburn
  • 51,587
  • 17
  • 154
  • 173