gpt4 book ai didi

java - 如何模拟 Rest Template 的 getForEntity() 方法

转载 作者:行者123 更新时间:2023-11-30 05:34:27 24 4
gpt4 key购买 nike

我是 mockito 的新手,需要一些帮助,可能是一些有关如何模拟 Rest Template 的 getForEntity 和 postForEntity 方法的示例。下面是我想通过模拟 getForEntity 方法来编写 Junit 测试用例的代码。

SomeService.java

class SomeService
{
//some private, static, final data members
public Map getService(String sNo, String uId, String en)
{
ResponseEntity <Map> response = new
RestTemplate().getForEntity("https://someurl.com/someService",
Map.class);
Map body = response.getBody();
//do something

HttpEntity<?> request = new HttpEntity <>(payLoad, headers);
//payload is Hash Map and headers is a LinkedMultiValueMap
ResponseEntity <Map> response = new RestTemplate().postForEntity(url,
request, headers);
return response.getBody();

}
}

我尝试用@Mock 和@InjectMocks 做一些事情。

TestSomeService.java

@RunWith(MockitoJunitRunner.class)
class TestSomeService
{
@Mock
RestTemplate restTemplate;
@InjectMocks
SomeService ser;
/*Some data members*/
@Before
{
HttpEntity <?> request = new HttpEntity<>(reqPayload, headers);
Mockito.when(restTemplate.getForEntity("theUrl",
Map.class)).thenReturn(new ResponseEntity <Map>(someMap,
HttpStatus.OK));
Mockito.when(restTemplate.postForEntity("anotherUrl", request,
Map.class)).thenReturn(new ResponseEntity <Map>(expectedMap,
HttpStatus.OK));

}
@Test
public void testGetService()
{
Map <String, Object> result = ser.getService("123", "abc", "QA");
}
}

最佳答案

当你调用特定值时,你必须用ArgumentMatchers.eq()包装它。但是,您也可以使用 anyString()any(Class class) 等。它们都是不言自明的。 Mockito tutorial .

@Before
public void init (){
MockitoAnnotations.initMocks(this);

HttpEntity <?> request = new HttpEntity<>(reqPayload, headers);

Mockito.when(restTemplate.getForEntity(ArgumentMatchers.eq("theUrl"),ArgumentMatchers.any(Map.class)))
.thenReturn(new ResponseEntity <Map>(someMap, HttpStatus.OK));
}

关于你的结构。这样你就可以通过构造函数注入(inject)RestTemplate

public class ServiceTester {

@Mock
private RestTemplate restTemplate;

private Service service;

@Before
public void init (){
MockitoAnnotations.initMocks(this);

service = new Service(restTemplate);

HttpEntity <?> request = new HttpEntity<>(reqPayload, headers);

Mockito.when(restTemplate.getForEntity(ArgumentMatchers.eq("theUrl"),ArgumentMatchers.any(Map.class)))
.thenReturn(new ResponseEntity <Map>(someMap, HttpStatus.OK));
}


}

class Service {

private RestTemplate template;

@Autowired
public Service(RestTemplate template) {
this.template = template;
}

public Map doSomething () {
// do something with template
}
}

关于java - 如何模拟 Rest Template 的 getForEntity() 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56893078/

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