首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何修复UnfinishedStubbingException

如何修复UnfinishedStubbingException
EN

Stack Overflow用户
提问于 2017-07-13 05:29:31
回答 1查看 1.1K关注 0票数 1
代码语言:javascript
复制
@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));

}

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

代码语言:javascript
复制
org.mockito.exceptions.misusing.UnfinishedStubbingException: 

在这里检测到未完成的顽固性: org.openmrs.addonindex.scheduled.FetchCoreVersionsListIT.testCoreVersionsJsonHandle(FetchCoreVersionsListIT.java:66)的->

我对创建测试用例非常陌生,所以请耐心地忍受我的一些愚蠢之处:)

EN

回答 1

Stack Overflow用户

发布于 2018-04-03 20:57:13

下面是如何在SpringBoot2.0中实现它:

代码语言:javascript
复制
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提供了两个不同的语法:Mockito - difference between doReturn() and when()

代码语言:javascript
复制
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));

还有其他的窍门,比如使用eq(String.class)而不仅仅是String.class。错误输出试图引导您完成此过程。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/45072078

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档