【发布时间】: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