作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我的服务类在下面,然后是它的测试-
@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;
}
}
@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<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()
调用。
关于spring-boot - 如何在 Mockito 测试中修复 RestTemplate.exchange 的空值响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45674149/
我是一名优秀的程序员,十分优秀!