gpt4 book ai didi

java - 如何修复 UnfinishedStubbingException

转载 作者:太空宇宙 更新时间:2023-11-04 11:19:37 29 4
gpt4 key购买 nike

@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: 

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

我对创建测试用例还很陌生,所以如果它有些愚蠢,请耐心等待:)

最佳答案

以下是使用 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 提供两种不同的语法: 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));

还有其他技巧,例如使用 eq(String.class) 而不仅仅是 String.class。错误输出试图引导您详细了解这一点。

关于java - 如何修复 UnfinishedStubbingException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45072078/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com