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

geo*_*rge 7 java junit spring spring-mvc

我尝试使用以下控制器

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

我使用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"));
   }
}
Run Code Online (Sandbox Code Playgroud)

如何将此params标签翻译为spring mvc junit?谢谢

Nik*_*sev 7

将param`reqType = delete'添加到url.

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