对于根据MediaType返回不同内容的路由进行单元测试,可以按照以下步骤进行:
以下是一个示例的Java单元测试代码:
import org.junit.Test;
import org.springframework.http.MediaType;
import org.springframework.mock.web.MockHttpServletRequest;
import org.springframework.mock.web.MockHttpServletResponse;
public class MyControllerTest {
@Test
public void testJsonRoute() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setRequestURI("/route");
request.addHeader("Accept", MediaType.APPLICATION_JSON_VALUE);
MockHttpServletResponse response = new MockHttpServletResponse();
MyController controller = new MyController();
controller.handleRoute(request, response);
// 验证响应结果
String expectedContent = "{\"message\":\"Hello, JSON!\"}";
assertEquals(expectedContent, response.getContentAsString());
assertEquals(MediaType.APPLICATION_JSON_VALUE, response.getContentType());
}
@Test
public void testXmlRoute() {
MockHttpServletRequest request = new MockHttpServletRequest();
request.setMethod("GET");
request.setRequestURI("/route");
request.addHeader("Accept", MediaType.APPLICATION_XML_VALUE);
MockHttpServletResponse response = new MockHttpServletResponse();
MyController controller = new MyController();
controller.handleRoute(request, response);
// 验证响应结果
String expectedContent = "<message>Hello, XML!</message>";
assertEquals(expectedContent, response.getContentAsString());
assertEquals(MediaType.APPLICATION_XML_VALUE, response.getContentType());
}
}
在这个示例中,我们使用了Spring的MockHttpServletRequest和MockHttpServletResponse来模拟请求和响应。通过设置请求的MediaType,然后调用被测试的路由方法,最后验证响应的内容和MediaType是否符合预期。
对于这个问题,腾讯云并没有特定的产品或链接与之相关。
领取专属 10元无门槛券
手把手带您无忧上云