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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32245785/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 19:53:27  来源:igfitidea点击:

How do I give request parameters for a POST using MockMvc

javaspringspring-mvcjunit

提问by george

I try to junit the following controller

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

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

I use params="reqType=delete" and this is I think the reason why junit fails to map to the controller. I tested all other controllers and they work fine without params tag to the controller. My junit config is:

我使用 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"));
   }
}

How do I translate this params tag to the spring mvc junit? Thank you

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

采纳答案by Nikolay Rusev

add param `reqType=delete' to url.

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

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