gpt4 book ai didi

java - 如何模拟 REST 模板交换?

转载 作者:IT老高 更新时间:2023-10-28 20:49:31 26 4
gpt4 key购买 nike

我有一项服务,我需要通过 rest 向外部服务器询问一些信息:

public class SomeService {

public List<ObjectA> getListofObjectsA() {
List<ObjectA> objectAList = new ArrayList<ObjectA>();
ParameterizedTypeReference<List<ObjectA>> typeRef = new ParameterizedTypeReference<List<ObjectA>>() {};
ResponseEntity<List<ObjectA>> responseEntity = restTemplate.exchange("/objects/get-objectA", HttpMethod.POST, new HttpEntity<>(ObjectAList), typeRef);
return responseEntity.getBody();
}
}

如何为 getListofObjectsA() 编写 JUnit 测试?

我尝试过以下方法:

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
private MockRestServiceServer mockServer;

@Mock
private RestTemplate restTemplate;

@Inject
private SomeService underTest;

@Before
public void setup() {
mockServer = MockRestServiceServer.createServer(restTemplate);
underTest = new SomeService(restTemplate);
mockServer.expect(requestTo("/objects/get-objectA")).andExpect(method(HttpMethod.POST))
.andRespond(withSuccess("{json list response}", MediaType.APPLICATION_JSON));
}

@Test
public void testGetObjectAList() {
List<ObjectA> res = underTest.getListofObjectsA();
Assert.assertEquals(myobjectA, res.get(0));
}

但是上面的代码不起作用,它表明 responseEntittynull。如何更正我的测试以正确模拟 restTemplate.exchange

最佳答案

您不需要 MockRestServiceServer 对象。注释是 @InjectMocks 而不是 @Inject。下面是一个应该可以工作的示例代码

@RunWith(MockitoJUnitRunner.class)
public class SomeServiceTest {
@Mock
private RestTemplate restTemplate;

@InjectMocks
private SomeService underTest;

@Test
public void testGetObjectAList() {
ObjectA myobjectA = new ObjectA();
//define the entity you want the exchange to return
ResponseEntity<List<ObjectA>> myEntity = new ResponseEntity<List<ObjectA>>(HttpStatus.ACCEPTED);
Mockito.when(restTemplate.exchange(
Matchers.eq("/objects/get-objectA"),
Matchers.eq(HttpMethod.POST),
Matchers.<HttpEntity<List<ObjectA>>>any(),
Matchers.<ParameterizedTypeReference<List<ObjectA>>>any())
).thenReturn(myEntity);

List<ObjectA> res = underTest.getListofObjectsA();
Assert.assertEquals(myobjectA, res.get(0));
}

关于java - 如何模拟 REST 模板交换?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39486521/

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