Rig*_*hto 3 junit spring-test mockito spring-boot spring-boot-test
我的服务类如下,其后是测试 -
@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;
}
}
Run Code Online (Sandbox Code Playgroud)
测试类:在我下面的测试类中,我看到ResponseEntity对象在调试时为null,导致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);
}
}
Run Code Online (Sandbox Code Playgroud)
当我调试测试时,我在主服务类的以下行获得了responseEntity的空值 -
ResponseEntity<String> responseEntity = restTemplate.exchange(uri,
HttpMethod.GET, entity,
String.class);
Run Code Online (Sandbox Code Playgroud)
这条指令......
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(ResponseEntity.class),
any(Class.class)
);
Run Code Online (Sandbox Code Playgroud)
......应该替换为:
doReturn(mockEntity).when(restTemplate).exchange(
any(URI.class),
any(HttpMethod.class),
any(HttpEntity.class),
any(Class.class)
);
Run Code Online (Sandbox Code Playgroud)
因为getStudentInfo()创建了一个HttpEntity(not ResponseEntity)的实例,然后将其传递给restTemplate.exchange()调用.
| 归档时间: |
|
| 查看次数: |
5610 次 |
| 最近记录: |