Spring Junit测试returns 404错误码
Spring Junit test returns 404 error code
我正在创建一个 Spring Junit class 来测试我的另一个 api。但是当我调用它时,它 return 我 404 并且测试用例失败了。
Junit 测试 class 是:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:config/spring-commonConfig.xml"})
public class SampleControllerTests {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testSampleWebService() throws Exception {
mockMvc.perform(post("/sample/{userJson}", "{\"id\":\"102312121\",\"text\":\"Hi user\",\"key\":\"FIRST\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$result", is("Hello ")))
.andExpect(jsonPath("$answerKey", is("")));
}
}
RestController class 是:
@RestController
public class SampleController {
private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
@Autowired private SampleService sService;
@RequestMapping(value = "${URL.SAMPLE}", method = RequestMethod.POST)
@ResponseBody
public String sampleWebService(@RequestBody String userJson){
String output="";
try{
output = sService.processMessage(userJson);
}
catch(Exception e){
e.printStackTrace();
}
return output;
}
}
我正在从 属性 文件加载 url 字符串。这样我就不会在控制器 class 中硬编码 url 而是动态映射它,所以这就是我通过下面提到的 class 加载 属性 文件的原因.
"URL.SAMPLE=/sample/{userJson}"
读取定义了url的属性文件的class:
@Configuration
@PropertySources(value = {
@PropertySource("classpath:/i18n/urlConfig.properties"),
@PropertySource("classpath:/i18n/responseConfig.properties")
})
public class ExternalizedConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
错误代码404表示,已连接到服务器但未获取我们请求的源。
谁能告诉我到底是什么问题?
谢谢,
阿图尔
您目前正在尝试使用 @RequestBody
从请求正文中解析 JSON 输入;但是,您没有将内容作为请求正文提交。
相反,您正尝试在 URL 中对请求正文进行编码,但它不会那样工作。
要修复它,您需要执行以下操作。
- 使用
/sample
作为请求路径(不是/sample/{userJson}
)
- 提供您的测试 JSON 输入作为请求的 body。
您可以按如下方式执行后者。
@Test
public void testSampleWebService() throws Exception {
String requestBody = "{\"id\":\"102312121\",\"text\":\"Hi user\",\"key\":\"FIRST\"}";
mockMvc.perform(post("/sample").content(requestBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$result", is("Hello ")))
.andExpect(jsonPath("$answerKey", is("")));
}
感谢您的回复。
我已经按照您的建议进行了更改,但错误仍然存在。
所以我再次搜索错误并找到了解决方案。
我在 Spring xml 文件中进行了更改。喜欢:
在 xml 文件中为 mvc 添加命名空间。
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<context:component-scan base-package="XXX" />
<mvc:annotation-driven />
在此之后它正在工作。
我正在创建一个 Spring Junit class 来测试我的另一个 api。但是当我调用它时,它 return 我 404 并且测试用例失败了。 Junit 测试 class 是:
@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(locations={"classpath:config/spring-commonConfig.xml"})
public class SampleControllerTests {
public static final MediaType APPLICATION_JSON_UTF8 = new MediaType(
MediaType.APPLICATION_JSON.getType(),
MediaType.APPLICATION_JSON.getSubtype(), Charset.forName("utf8"));
private MockMvc mockMvc;
@Autowired
private WebApplicationContext webApplicationContext;
@Before
public void setup() {
this.mockMvc = MockMvcBuilders.webAppContextSetup(webApplicationContext).build();
}
@Test
public void testSampleWebService() throws Exception {
mockMvc.perform(post("/sample/{userJson}", "{\"id\":\"102312121\",\"text\":\"Hi user\",\"key\":\"FIRST\"}"))
.andExpect(status().isOk())
.andExpect(jsonPath("$result", is("Hello ")))
.andExpect(jsonPath("$answerKey", is("")));
}
}
RestController class 是:
@RestController
public class SampleController {
private static final Logger logger = LoggerFactory.getLogger(SampleController.class);
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSS").create();
@Autowired private SampleService sService;
@RequestMapping(value = "${URL.SAMPLE}", method = RequestMethod.POST)
@ResponseBody
public String sampleWebService(@RequestBody String userJson){
String output="";
try{
output = sService.processMessage(userJson);
}
catch(Exception e){
e.printStackTrace();
}
return output;
}
}
我正在从 属性 文件加载 url 字符串。这样我就不会在控制器 class 中硬编码 url 而是动态映射它,所以这就是我通过下面提到的 class 加载 属性 文件的原因.
"URL.SAMPLE=/sample/{userJson}"
读取定义了url的属性文件的class:
@Configuration
@PropertySources(value = {
@PropertySource("classpath:/i18n/urlConfig.properties"),
@PropertySource("classpath:/i18n/responseConfig.properties")
})
public class ExternalizedConfig {
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfigurer() {
return new PropertySourcesPlaceholderConfigurer();
}
}
错误代码404表示,已连接到服务器但未获取我们请求的源。 谁能告诉我到底是什么问题?
谢谢, 阿图尔
您目前正在尝试使用 @RequestBody
从请求正文中解析 JSON 输入;但是,您没有将内容作为请求正文提交。
相反,您正尝试在 URL 中对请求正文进行编码,但它不会那样工作。
要修复它,您需要执行以下操作。
- 使用
/sample
作为请求路径(不是/sample/{userJson}
) - 提供您的测试 JSON 输入作为请求的 body。
您可以按如下方式执行后者。
@Test
public void testSampleWebService() throws Exception {
String requestBody = "{\"id\":\"102312121\",\"text\":\"Hi user\",\"key\":\"FIRST\"}";
mockMvc.perform(post("/sample").content(requestBody))
.andExpect(status().isOk())
.andExpect(jsonPath("$result", is("Hello ")))
.andExpect(jsonPath("$answerKey", is("")));
}
感谢您的回复。
我已经按照您的建议进行了更改,但错误仍然存在。
所以我再次搜索错误并找到了解决方案。
我在 Spring xml 文件中进行了更改。喜欢:
在 xml 文件中为 mvc 添加命名空间。
xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
<context:component-scan base-package="XXX" />
<mvc:annotation-driven />
在此之后它正在工作。