我的服务类在下面,然后是它的测试 -
@Service
public class MyServiceImpl implements MyService {
@Autowired
private RestTemplate restTemplate;
@Override
public StudentInfo getStudentInfo(String name) {
HttpHeaders headers = new HttpHeaders();
headers.set("Accept", MediaType.APPLICATION_JSON_VALUE);
HttpEntity entity = new HttpEntity(headers);
StudentInfo student = null;
URI uri = new URI("http:\someurl.com");
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);
if (responseEntity.getStatusCode().equals(HttpStatus.NO_CONTENT)) {
throw new Exception("Student absent");
}else {
ObjectMapper mapper = new ObjectMapper();
StudentInfo student = mapper.readValue(responseEntity.getBody(), StudentInfo.class);
}
return student;
}
}
测试类:在下面的测试类中,我在调试时看到 ResponseEntity 对象为空,这会导致 NPE。
@RunWith(MockitoJUnitRunner.class)
public class MyServiceImplTest {
@InjectMocks
private MyService service = new MyServiceImpl();
@Mock
private RestTemplate restTemplate;
@Before
public void setUp() {
MockitoAnnotations.initMocks(this);
}
@Test
public void testStudentGetterResponse() {
ResponseEntity<String> mockEntity = Mockito.spy(new ResponseEntity({"id" : 1, "name" : "Rutzen"}, HttpStatus.OK));
doReturn(mockEntity).when(restTemplate).exchange(any(URI.class), any(HttpMethod.class), any(ResponseEntity.class),
any(Class.class));
StudentInfo info = service.getStudentInfo("testuser");
Assert.assertNotNull(info);
}
}
当我调试测试时,我在主服务类的下一行得到 responseEntity 的空值 -
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);
此指令...
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(ResponseEntity.class),
any(Class.class)
);
。应替换为:
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(HttpEntity.class),
any(Class.class)
);
因为getStudentInfo()
会创建一个HttpEntity
(不是ResponseEntity
(的实例,然后将其传递给restTemplate.exchange()
调用。
因为接受的答案是正确的。我正在为已经接受的答案添加一些东西。
这似乎有点奇怪,但我通过查看接受的答案来解决问题,并且评论是由提出问题的用户添加的。
替换此
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(ResponseEntity.class),
any(Class.class)
);
跟
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(HttpEntity.class),
any(Class.class)
);
如果您仍然收到错误,请不要使用多行。仅使用一行并按如下所示替换它。
doReturn(mockEntity).when(restTemplate).exchange(any(URI.class), any(HttpMethod.class), any(HttpEntity.class), any(Class.class)
);
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);
在字符串的情况下我不会工作[]
喜欢
ResponseEntity<String[]> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String[].class);