【问题标题】:How do I give request parameters for a POST using MockMvc如何使用 MockMvc 为 POST 提供请求参数
【发布时间】:2015-08-27 09:37:03
【问题描述】:

我尝试联合以下控制器

  @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 无法映射到控制器的原因。我测试了所有其他控制器,它们在没有控制器的参数标签的情况下工作正常。我的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?谢谢

【问题讨论】:

    标签: java spring spring-mvc junit


    【解决方案1】:

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

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

    【讨论】:

    • 这确实有效,但我不明白为什么 this.mockMvc.perform(post("/pendingactions.htm","?reqType=delete") 不起作用..它仍然应该追加它到 uri..
    【解决方案2】:

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

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

    【讨论】:

      猜你喜欢
      • 2017-10-28
      • 1970-01-01
      • 2016-06-14
      • 1970-01-01
      • 2014-02-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-08
      相关资源
      最近更新 更多