Server-Side Validations and Spring Boot Testing
1. Server-Side Validations
Layers for Validation
- Presentation Logic (P.L)
- To be performed in Rest Controller
- Business Logic (B.L)
Development Steps for Adding Server-Side P.L Validations
- Add Dependency
- Add spring boot validation starter dependency
- pom.xml (done already in spring boot backend template)
- Validate Request Body
- Add @Valid annotation along with @RequestBody (de-serial)
- Add validation rules (annotations - jakarta, spring , hibernate-validator) on DTO fields.
- eg - @NotNull , @NotEmpty , @NotBlank , @Email , @Pattern, @Length,@Min , @Max , @Future ,@Past, @DateTimeFormat ....
- More details -
- @NotEmpty
- =>Strings cannot be null and must have at least one character including whitespace
- for collections must contain at least 1 element
- @NotBlank
- strings not null n must contain some content after whitespace trimming
- @NotNull
- => simply not null (use it typically on non string fields - eg LocalDate , enum , double ...)
- In case of P.L failure , Spring throws
- MethodArgumentNotValidException
- add new exception handler method(@ExceptionHandler) in global exception handler class(@RestControllerAdvice)
- Validate PathVariable or Request Parameter
- Add @Validated annotation
- on rest controller class
- use same validation annotations with @RequestParam | @PathVariable
- In case of P.L failure , Spring throws
- ConstraintViolationException
3.1 User Signup Endpoint
- Add it for User sign up end point n test.
2. Spring Boot Testing
- Unit Testing
- Integration Testing
Task: Add Unit Test for Data Layer
- Methods to Test:
- getRestaurantAndMenu(Long id);
- findTop3ByUserRoleOrderBySubscriptionAmountDesc(UserRole role);
- Write in DAO Layer:
- Get list of user’s last name from specified city
- Write its test case
3. Spring AOP
- [No specific content provided for this section]