gpt4 book ai didi

Spring 3.2.2 : MockMVC, 返回空结果

转载 作者:行者123 更新时间:2023-11-28 20:01:24 24 4
gpt4 key购买 nike

我有以下 REST Controller

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

此 Controller 在 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 的特定期望替换 model() 部分时,XML 和 JSON 字符串始终返回空。

我花了几天时间试图理解这一点,我对 Java 比较陌生,对 Spring 更陌生。你能告诉我在哪里可以解决这个问题吗?

作为附加信息,我在任何地方都放置了日志消息(使用 sfj4l),但是当使用 Junit 运行时,DAO 中的日志消息有效,测试模块本身中的日志消息有效,但我的 REST Controller 中的日志消息没有出现。

就像是匹配了GET函数,但是函数的内容一直没有执行,得到的响应是空的。尽管如此,我对 isOk() 的调用还是成功的。

最佳答案

“No ModelAndView Found”是正确的。使用@ResponseBody,返回值直接写入响应主体。没有模型,没有 View 分辨率等。

更一般地说,理想情况下,侧重于从客户的角度测试请求的结果。这包括响应 header 、正文和响应状态。测试其他通常对客户端不可见的结果,例如更谨慎地测试模型属性。

关于Spring 3.2.2 : MockMVC, 返回空结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15618037/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com