MockMvc 响应返回 404,预期响应 201

Posted

技术标签:

【中文标题】MockMvc 响应返回 404,预期响应 201【英文标题】:MockMvc response returns 404, expected response 201 【发布时间】:2021-01-13 05:58:22 【问题描述】:

我是在 Spring Boot 中对 REST API 进行单元测试的新手。

我希望响应状态为已创建,但我收到了一个 PAGE NOT FOUND 错误。

下面是代码:-

UserControllerUnitTests

@SpringBootTest
@ContextConfiguration(classes =  CommonConfig.class, SecurityConfig.class)
@RunWith(SpringRunner.class)
class UserControllerUnitTests 

    private static ObjectMapper mapper;
    private static final String URI = "/users";

    MockMvc mvc;

    @Autowired
    WebApplicationContext webAppContext;

    @Mock
    UserService userService;

    MvcResult mvcResult;

    @BeforeAll
    static void setUp() 
        mapper = new ObjectMapper();
    

    @BeforeEach
    void initialize() throws Exception 
        mvc = MockMvcBuilders.webAppContextSetup(webAppContext).build();
    ....
    ....
    ....
   
    void shouldReturnStatusCreatedIfValidUserPassedForPostUser(long index) throws Exception 
        int expectedStatus = HttpStatus.CREATED.value();
        UserDAO returnUser;
    
        UserDAO user = userList.get(index);
        userList.remove(index);
        String jsonContent = mapper.writeValueAsString(user);
    
        user.setId(index);
        user.setEncryptedPassword(null);
    
        Mockito.when(userService.addUser(Mockito.any())).thenReturn(user);
    
        mvcResult = mvc.perform(MockMvcRequestBuilders.post(URI)
            .accept(MediaType.APPLICATION_JSON)
            .contentType(MediaType.APPLICATION_JSON)
            .content(jsonContent)).andReturn();
    
        //Mockito.verify(userService, Mockito.times(1)).addUser(Mockito.any());
    
        int actualStatus = mvcResult.getResponse().getStatus();
        Assert.assertEquals("Response status should be CREATED", expectedStatus, actualStatus);
    
        jsonContent = mvcResult.getResponse().getContentAsString();
        returnUser = mapper.readValue(jsonContent, UserDAO.class);
    
        Assert.assertEquals("EncryptedPassword should not be returned", null, 
                                          returnUser.getEncryptedPassword());
    

用户控制器类

 @RestController
 @RequestMapping("users/")
 public class UserController 

     UserService userService;
    
     @Autowired
     public UserController(UserService userService) 
         this.userService = userService;
     
     ....
     ....
     ....

     @PostMapping(path = "",
            consumes =  MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON , 
            produces =  MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON )
    public ResponseEntity<UserDAO> createUser(@Valid @RequestBody UserDAO user) 
        String password = user.getEncryptedPassword();
        user.setEncryptedPassword(null);
        UserDAO retreivedUser;
    
        if(user.getId() != 0)
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    
        user.setEncryptedPassword(password);
        retreivedUser = userService.addUser(user);
        if(retreivedUser != null)
            return new ResponseEntity<>(retreivedUser, HttpStatus.CREATED);
        return new ResponseEntity<>(HttpStatus.CONFLICT);
    

完整代码见https://github.com/vineethmaller/springboot-userservice

【问题讨论】:

【参考方案1】:

我发现了一些错误:

    摆脱 ContextConfiguration

    @SpringBootTest
    // @ContextConfiguration(classes =  CommonConfig.class, SecurityConfig.class)
    @RunWith(SpringRunner.class)
    class UserControllerUnitTests 
    

    在控制器上指定正确的映射(无斜线)

    @RestController
    @RequestMapping("users")
    public class UserController 
    

    您设置了未在测试中使用的 UserService 模拟。你是说@MockBean 吗?

    @MockBean
    UserService userService;
    

【讨论】:

感谢工作。我还包含了一个 bootstrap.yml 属性文件来测试/资源以禁用 Spring 云总线。

以上是关于MockMvc 响应返回 404,预期响应 201的主要内容,如果未能解决你的问题,请参考以下文章

如何修复来自 Axios 的随机 http 请求(404 响应)

当普罗米修斯端点正在调用时,MockMvc 收到 404

在节点中将 JSONP 响应字符串转换为 JSON

Junit MockMvc 使用 URL 中的路径变量执行 POST,返回 404 未找到

Mocha:未捕获的 AssertionError:预期 200 为 404

如何使用 mockMvc 检查响应正文中的 JSON