簡體   English   中英

@Pattern 注釋在 junit 4 中不起作用

[英]@Pattern annotation is not working in junit 4

我正在處理一個示例 spring 啟動應用程序,它為用戶執行 CRUD 操作。

我創建了一個用戶UsersController.java是 controller 代碼。

UsersController.java

    @PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Authorization")
    @ApiOperation(value = "API endpoint to save users", notes = "API endpoint to save users")
    @ApiResponses(value = {
        @ApiResponse(code = 200, message = ErrorConstants.OK),
        @ApiResponse(code = 400, message = ErrorConstants.BAD_REQUEST),
        @ApiResponse(code = 403, message = ErrorConstants.FORBIDDEN),
        @ApiResponse(code = 500, message = ErrorConstants.INTERNAL_SERVER_ERROR) }
    )
    public ResponseEntity<?> addUsers(@Valid @RequestBody UserDto userDto) {
        try {
            return new ResponseEntity<>(userService.createUsers(userDto), HttpStatus.OK);
        } catch (BadRequestException e) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        } catch (Exception e) {
            return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
        }
    }

DTO如下

UserDto.java

    @JsonInclude(Include.NON_NULL)
    @JsonIgnoreProperties(ignoreUnknown = true)
    public class UserDto {
    
        private String id;
    
        @Size(min = 4, max = 36, message = "Name should be between 4 to 36 characters long.")
        @Pattern(regexp = "^[^&+;=#<>*{}@:]*$", message = "Name field Should not contain special chars")
        private String name;
    
        private String address;
        
        private String mobileNo;
    }

如您所見,我已將驗證添加到name字段。 此外,我創建了一個 controller advise 來處理異常。

ExceptionControllerAdvise.java

    import org.springframework.web.bind.MethodArgumentNotValidException;
    import org.springframework.web.bind.annotation.ExceptionHandler;
    
    
    @RestControllerAdvice
    public class ExceptionControllerAdvise {
    
        @ExceptionHandler(value = MethodArgumentNotValidException.class)
        public ResponseEntity<ErrorResponse> validException(MethodArgumentNotValidException exception) {
            return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
        }
    }

如果注釋字段引發任何驗證異常,上面的 class 將返回錯誤。

當我運行應用程序並使用無效名稱(包含特殊字符的名稱)調用 API 時,我收到 400 錯誤請求異常。

但是當我嘗試為無效數據編寫 junit 測試用例時,測試用例通過了。 (即@Pattern注釋不適用於 junit)

這是我的樣品 junit 用於測試。

    @Test
    public void test0_createUsersWithInvalidName() {
        UserDto dto = new UserDto();
        dto.setName("Apple&sons!")
        dto.setAddress("abc");
        ResponseEntity<?> response = usersController.addUsers(dto)
        assertTrue(response.getStatusCode().equals(HttpStatus.BAD_REQUEST));
    }

上面的測試用例通過了,但是我收到一個java.lang.AssertionError錯誤; 當我調試這個問題時,我發現我收到的狀態是200 OK而不是400 BAD REQUEST

那么,有人可以在這里幫助我嗎? 謝謝

如果你想在你的 controller 中測試你的bean validation規則,你可以通過 mocking 將在你的服務 class 中發生的異常或在你的集成測試中通過模擬錯誤值來完成。 您也可以改進controller中的代碼。 在這里,您在catch部分返回了一個BAD_REQUEST ,它是您的ControllerAdvice class 的角色。相反,您應該拋出一個BadRequestException請求異常,該異常將被傳輸到您的ControllerAdvice

Controller

@PostMapping(value = "/users", consumes = MediaType.APPLICATION_JSON_VALUE, produces = MediaType.APPLICATION_JSON_VALUE, headers = "Authorization")
@ApiOperation(value = "API endpoint to save users", notes = "API endpoint to save users")
@ApiResponses(value = {
    @ApiResponse(code = 200, message = ErrorConstants.OK),
    @ApiResponse(code = 400, message = ErrorConstants.BAD_REQUEST),
    @ApiResponse(code = 403, message = ErrorConstants.FORBIDDEN),
    @ApiResponse(code = 500, message = ErrorConstants.INTERNAL_SERVER_ERROR) }
)
public ResponseEntity<?> addUsers(@Valid @RequestBody UserDto userDto) {
    try {
        return new ResponseEntity<>(userService.createUsers(userDto), HttpStatus.OK);
    } catch (MethodArgumentNotValidException e) {
        throw new BadRequestException("YOUR MESSAGE", e); // the e in parameter to get the root cause if you send message from your validation
    } catch (Exception e) {
        throw new InternalServerErrorException("YOUR MESSAGE", e); // the e in parameter to get the root cause
    }
}

Controller 咨詢

@RestControllerAdvice
public class ExceptionControllerAdvise {

    @ExceptionHandler(value = BadRequestException.class)
    public ResponseEntity<ErrorResponse> validException(BadRequestException exception) {
        return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
    }

    @ExceptionHandler(value = InternalServerErrorException.class)
    public ResponseEntity<ErrorResponse> serverException(InternalServerErrorExceptionexception) {
        return new ResponseEntity<>(HttpStatus.INTERNAL_SERVER_ERROR);
    }
}

測試 class

@Test
public void test0_createUsersWithInvalidName() {
   
    ...
    
    when(userService
    .createUsers(userDto))
    .thenThrow(MethodArgumentNotValidException.class);

   ...
   // Here use mockMvc instead
}

您的這部分測試代碼將用於您的集成測試:

UserDto dto = new UserDto();
dto.setName("Apple&sons!")
dto.setAddress("abc");

另外,你如何構建你的ErrorResponse

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM