我有一项服务,需要通过休息向外部服务器询问一些信息:
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(); } }
我该如何编写JUnit测试getListofObjectsA()?
getListofObjectsA()
我尝试了以下方法:
@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?
responseEntitty
null
restTemplate.exchange
您不需要MockRestServiceServer对象。注释@InjectMocks不是@Inject。以下是应该工作的示例代码
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)); }