【问题标题】:Spring Junit test returns 404 error codeSpring Junit 测试返回 404 错误代码
【发布时间】:2016-09-15 10:00:00
【问题描述】:

我正在创建一个 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=/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 的意思是,它连接到服务器但没有得到我们请求的源。 谁能告诉我到底是什么问题?

谢谢, 阿图尔

【问题讨论】:

    标签: spring-test spring-test-mvc


    【解决方案1】:

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

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

    要修复它,您需要执行以下操作。

    1. 使用/sample作为请求路径(不是/sample/{userJson}
    2. 提供您的测试 JSON 输入作为请求的正文

    您可以按如下方式进行后者。

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

    【讨论】:

      【解决方案2】:

      感谢您的回复。

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

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

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

      之后它就可以工作了。

      【讨论】:

        猜你喜欢
        • 2012-01-04
        • 1970-01-01
        • 2012-05-15
        • 2017-09-06
        • 1970-01-01
        • 1970-01-01
        • 2022-12-17
        • 2012-10-18
        • 1970-01-01
        相关资源
        最近更新 更多