如何修复UnfinishedStubbingException

时间:2017-07-13 05:29:32

标签: java mockito integration-testing

@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));

}

运行测试时,我收到以下错误

org.mockito.exceptions.misusing.UnfinishedStubbingException: 

此处检测到未完成的存根: - >在org.openmrs.addonindex.scheduled.FetchCoreVersionsListIT.testCoreVersionsJsonHandle(FetchCoreVersionsListIT.java:66)

我很擅长创建测试用例,如果它有些愚蠢的话,请耐心等待我:)

1 个答案:

答案 0 :(得分:0)

以下是使用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);
    }

}