Spring Junit测试返回404错误代码

时间:2016-09-15 10:00:01

标签: spring-test spring-test-mvc

我正在创建一个Spring Junit类来测试我的其中一个api。但是当我打电话给它时,它返回404并且测试用例失败了。 Junit测试类是:

@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类是:

@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字符串。这样我就不会对控制器类中的url进行硬编码,而是动态映射它,这就是我通过类加载属性文件的原因,我在下面提到过。

  

" URL.SAMPLE = /样品/ {userJson}"

读取定义url的属性文件的类:

@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表示它连接到服务器但未获取我们请求的源。 谁能告诉我究竟是什么问题?

谢谢, 阿图尔

2 个答案:

答案 0 :(得分:1)

您当前正在尝试使用@RequestBody从请求正文中解析JSON输入;但是,您没有将内容作为请求正文提交。

相反,您试图在URL中对请求正文进行编码,但它不会像那样工作。

要解决此问题,您需要执行以下操作。

  1. 使用/sample作为请求路径(不是/sample/{userJson}
  2. 提供测试JSON输入作为请求的正文
  3. 您可以按照以下方式执行后者。

    @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("")));
    }   
    

答案 1 :(得分:0)

感谢您的回复。

我已根据您的建议进行了更改,但错误仍然存​​在。

所以我再次搜索错误并找到解决方案。

我在Spring xml文件中进行了更改。像:

在mvc的xml文件中添加命名空间。

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 />

在此之后它正在运作。