繁体   English   中英

如何使用 MockMvc 为 POST 提供请求参数

[英]How do I give request parameters for a POST using MockMvc

我尝试对以下控制器进行联合

  @RequestMapping(value="actions.htm", params="reqType=delete",method=RequestMethod.POST)
  @ResponseBody
  public String deletePendingAction(@RequestParam("aPk") Long aPk)
  {
    pendingActionsService.deletePendingAction(aPk);
    return "Deleted";
  }

我使用 params="reqType=delete" 这就是我认为 junit 无法映射到控制器的原因。 我测试了所有其他控制器,它们在没有 params 标签到控制器的情况下工作正常。 我的junit配置是:

@RunWith(SpringJUnit4ClassRunner.class)
@WebAppConfiguration
@ContextConfiguration(classes = ApplicationConfig.class,loader = AnnotationConfigWebContextLoader.class)
@TransactionConfiguration(defaultRollback = true)
@Transactional
public class JUnitTests {

  @Autowired
  private WebApplicationContext wac;

  private MockMvc mockMvc;

   @Before
   public void SetupContext()
   {
     this.mockMvc = MockMvcBuilders.webAppContextSetup(this.wac).build();
   }

   @Test
   public void testController() throws Exception
   {
      this.mockMvc.perform(post("/actions.htm","reqType=delete").param("aPk","2"));
   }
}

如何将此 params 标记转换为 spring mvc junit? 谢谢

将参数`reqType=delete' 添加到 url。

this.mockMvc.perform(post("/actions.htm?reqType=delete")
                .param("aPk", "2")).andReturn().getResponse().getStatus());

事实上,测试应该是这样的,基于你的控制器:

import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
import org.junit.Assert;

final MvcResult result = mockMvc
       .perform(post("/actions.htm")
                     .param("reqType", "delete")
                     .param("aPk", "2"))
       .andExpect(
                status().isOk()
       .andReturn());

final String content = result.getResponse().getContentAsString();
Assert.assertEquals("Deleted", content);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM