繁体   English   中英

使用Mockido错误的POST请求的单元测试

[英]Unit testing for POST request using Mockido error

我在测试时期望的状态是200,但是现在我得到的是404。

我对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。

我创建Test类的方式是这样的:

    @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原始有效负载中使用的内容相同的内容?

谢谢。

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

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

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

暂无
暂无

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

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