我有以下的REST控制器春3.2.2:MockMVC,返回空结果
@Controller
@RequestMapping("/rest/transceptors")
public class TransceptorRestController
{
@Autowired
private TransceptorDao transceptorDao;
@RequestMapping(value="/get/{idTransceptor}", method=RequestMethod.GET)
public @ResponseBody Transceptor getOne(@PathVariable("idTransceptor") Long idTransceptor)
{
return transceptorDao.searchByIdTransceptor(idTransceptor);
}
}
在JBoss中运行时,其结果是如预期该控制器正常工作。我使用Postman(Google Chrome的REST测试扩展),我可以在XML和JSON中获得正确的结果。
但是,我使用MockMVC进行测试时遇到了问题。
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(
locations={
"classpath:test-servlet-context.xml"
})
@WebAppConfiguration
public class TransceptorRestControllerTest {
@Autowired
private WebApplicationContext wac;
private MockMvc mockMvc;
@Before
public void setup()
{
mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
}
@Test
public void testRoot() throws Exception
{
mockMvc.perform(get("/")).
andExpect(status().isOk());
}
@Test
public void testGet() throws Exception
{
mockMvc.perform(get("/rest/transceptors/get/1"))
.andExpect(status().isOk())
.andDo(print())
.andExpect(model().attribute("name", equals("Test_Name_1")));
}
TestRoot测试工作正常。但是,当我尝试使用andExpect(model()...我收到消息“No ModelAndView Found”时,XML和JSON字符串始终返回空。
我花了几天试图理解这一点,我是相当新的Java和更多的新春。你能告诉我我在哪里可以寻找到解决这个问题?
由于adittional信息,我已经将日志消息(包含sfj4l)放到了每个地方,但是在使用Junit运行时,DAO中的日志消息起作用,Test模块中的日志消息本身可以正常工作,但是REST控制器中的日志消息不会显示。
就像GET函数匹配,但函数的内容永远不会执行,并获得空的响应。尽管如此,我对isOk()的呼叫是成功的。
如果ModelAndView是空的,我明白它。但是,不应该返回正文中的XML或JSON内容吗?我这样说是因为当_andpath(_)使用_xpath_或_json_函数时,结果也是空的。我收到XML格式的“格式错误的xml,第1行第1列”或JSON格式的“没有json数据”。另外,当使用_andDo(print())时,当我检查控制台输出时,主体也会返回空。 – devnull 2013-03-28 14:26:56
另外,我应该补充说,只使用_andExpect(content()。string(_ ...这也会返回空结果,不是ModelAndView的问题。 – devnull 2013-04-02 21:35:32
@devnull,同样的问题在这里。你有没有想过? – Nikita 2013-09-04 15:42:33