我正在尝试为一个使用RestTemplate的REST Web服务客户端编写Junit。
以下是 REST 模板的方法调用:
final ResponseEntity<LogDateVO[]> result = restTemplate.postForEntity(url, LogDateInputVO, LogDateVO[].class);
在我的测试课程中,我正在尝试以下内容:
mockServer.expect(requestTo("http://abc.def.pvt:80/testOperations/api/traffic/logs/")).andExpect(method(HttpMethod.POST))
.andRespond(MockRestResponseCreators.withSuccess("{ \"id\" : \"42\", \"name\" : \"Holiday Inn\"}", MediaType.APPLICATION_JSON));
我无法得到结果而无法继续这种方法,我需要一些帮助才能得到这个。
我的意图是当我的restTemplate
被调用时,它应检查上述预期并返回一些数据的成功。
答案 0 :(得分:1)
假设测试中的类有一个使用RestTemplate调用postForEntity
的方法。有关详情,请查看this
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
@Service
public class SimpleRestService {
@Autowired
private RestTemplate restTemplate;
public String getMessage() {
String result;
String httpResult = restTemplate.getForObject("http://google.com",
String.class);
result = "Message SUCCESS result: " + httpResult;
return result;
}
}
您的测试类应如下所示:
@ContextConfiguration(locations = {"classpath:aap.xml"})
public class SimpleRestServiceFunctionalTest extends AbstractJUnit4SpringContextTests {
@Autowired
private SimpleRestService simpleRestService;
@Autowired
private RestTemplate restTemplate;
private MockRestServiceServer mockServer;
@Before
public void setUp() {
mockServer = MockRestServiceServer.createServer(restTemplate);
}
@Test
public void testGetMessage() {
mockServer.expect(requestTo("http://google.com")).andExpect(method(HttpMethod.GET))
.andRespond(withSuccess("resultSuccess", MediaType.TEXT_PLAIN));
String result = simpleRestService.getMessage();
mockServer.verify();
assertThat(result, allOf(containsString("SUCCESS"), containsString("resultSuccess")));
}
@Test
public void testGetMessage_500() {
mockServer.expect(requestTo("http://google.com")).andExpect(method(HttpMethod.GET))
.andRespond(withServerError());
String result = simpleRestService.getMessage();
mockServer.verify();
assertThat(result, allOf(containsString("FAILED"), containsString("500")));
}
@Test
public void testGetMessage_404() {
mockServer.expect(requestTo("http://google.com")).andExpect(method(HttpMethod.GET))
.andRespond(withStatus(HttpStatus.NOT_FOUND));
String result = simpleRestService.getMessage();
mockServer.verify();
assertThat(result, allOf(containsString("FAILED"), containsString("404")));
}
}