我有一项服务,我需要通过 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));
}
但是上面的代码不起作用,它表明 responseEntitty
是 null
。如何纠正我的测试以正确模拟 restTemplate.exchange
?
原文由 Akka Jaworek 发布,翻译遵循 CC BY-SA 4.0 许可协议
您不需要
MockRestServiceServer
对象。注释是@InjectMocks
不是@Inject
。下面是一个应该工作的示例代码