2017-06-16 55 views
2

我期望在测试时的状态为200,但现在我得到了404。使用Mockido错误对POST请求进行单元测试

我对Mockido来说是相当新的,所以如果有一些简单的东西我错过了。请告诉我。

我在我的控制器中创建了一个POST请求,该请求需要一个Long对象列表。如果没有异常情况发生,为身份返回OK:

@PostMapping(path = "/postlist") 
public ResponseEntity<Void> updateAllInList(@RequestBody List<Long> ids) { 
    try { 
     // method from ControllerService.java here using ids 
     return ResponseEntity.status(HttpStatus.OK).body(null); 
    } catch (InvalidContentException e) { 
     return ResponseEntity.status(HttpStatus.UNPROCESSABLE_ENTITY).body(null); 
    } 

发帖时使用REST客户端,我得到正确的结果。原始有效载荷我张贴是这样的:

[ 
    2, 1 
] 

然而,单元测试是给我一个404

我创建了测试类是这样的方式:

@RunWith(SpringJUnit4ClassRunner.class) 
    @WebAppConfiguration 
    @ContextHierarchy({ @ContextConfiguration(classes = RootConfiguration.class), @ContextConfiguration(classes = WebConfiguration.class) }) 
    @Category(UnitTest.class) 
    public class ControllerTest { 

     private static final String POST_REQUEST = "[ 2, 1 ]"; 

     @Autowired private WebApplicationContext webApplicationContext; 
     @Autowired private ControllerService controllerService; 

     private MockMvc mockMvc; 


     @Before 
     public void setUp() throws Exception { 

       this.mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build(); 

       doNothing().when(this.controllerService).updateAllInList(anyList()); 
      doThrow(InvalidContentException.class).when(this.controllerService).updateAllInList(null); 
     } 

     @Test 
     public void updateList() throws Exception { 
      this.mockMvc.perform(post("http://testhost/api/configuration/postlist").contentType(MediaType.APPLICATION_JSON_UTF8).content(POST_REQUEST)) 
        .andExpect(status().isOk()); 
     } 


     @Configuration 
     static class RootConfiguration { 


      @Bean 
      public ControllerService ControllerService() { 
       return Mockito.mock(ControllerService.class); 
      } 
     } 


     @Configuration 
     @EnableWebMvc 
     static class WebConfiguration extends WebMvcConfigurerAdapter { 

      @Autowired 
      private ControllerService controllerService; 


      @Bean 
      public Controller controller() { 
        return new Controller(controllerService); 
      } 
     } 
    } 

我理论是,在我的测试课中,我插入了错误的内容。但为什么我们不能插入与真正的POST原始有效载荷中使用的内容相同的内容?

谢谢。

+0

的POST_REQUEST串看起来并不像JSON给我吗? –

+0

@KarlNicholas嗨,如果我的原始有效负载在发布时以这种格式工作,是否有一些我错过了导致测试失败的格式?我猜一些额外的字符会在发布时自动添加到原始有效负载,但它们是什么?谢谢。 – pike

+0

404找不到:是'http:// testhost/api/configuration/postlist'一个真实的URL? –

回答

0

当您使用MockMvc时,想要触发控制器的映射,而不是HTTP服务器。

而不是mockMvc.perform(post("http://testhost/api/configuration/postlist")...

尝试mockMvc.perform(post("/configuration/postlist")...

+0

感谢您的回答。但是,即使尝试了我的映射的所有组合,我仍然得到了404。你认为我的内容和给定的(在设置方法中)是正确的吗? – pike

相关问题