BAEL-6695 Boolean Validation in Spring Boot
BAEL-6695 Boolean Validation in Spring Boot
This commit is contained in:
parent
2a574249c1
commit
6300c41290
|
@ -104,6 +104,7 @@
|
|||
<module>spring-boot-springdoc-2</module>
|
||||
<module>spring-boot-documentation</module>
|
||||
<module>spring-boot-3-url-matching</module>
|
||||
<module>spring-boot-validations</module>
|
||||
</modules>
|
||||
|
||||
<dependencyManagement>
|
||||
|
|
|
@ -0,0 +1,38 @@
|
|||
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
<parent>
|
||||
<groupId>com.baeldung.spring-boot-modules</groupId>
|
||||
<artifactId>spring-boot-modules</artifactId>
|
||||
<version>1.0.0-SNAPSHOT</version>
|
||||
</parent>
|
||||
<artifactId>spring-boot-validations</artifactId>
|
||||
<name>spring-boot-validations</name>
|
||||
<description>Demo of Validations in Spring Boot</description>
|
||||
<dependencies>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-web</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-test</artifactId>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-starter-validation</artifactId>
|
||||
</dependency>
|
||||
<dependency>
|
||||
<groupId>org.projectlombok</groupId>
|
||||
<artifactId>lombok</artifactId>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.springframework.boot</groupId>
|
||||
<artifactId>spring-boot-maven-plugin</artifactId>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
|
@ -0,0 +1,12 @@
|
|||
package com.baeldung;
|
||||
|
||||
import org.springframework.boot.SpringApplication;
|
||||
import org.springframework.boot.autoconfigure.SpringBootApplication;
|
||||
|
||||
@SpringBootApplication
|
||||
public class Application {
|
||||
|
||||
public static void main(String[] args) {
|
||||
SpringApplication.run(Application.class, args);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,19 @@
|
|||
package com.baeldung.controller;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.http.ResponseEntity;
|
||||
import org.springframework.web.bind.annotation.PostMapping;
|
||||
import org.springframework.web.bind.annotation.RequestBody;
|
||||
import org.springframework.web.bind.annotation.RestController;
|
||||
|
||||
import com.baeldung.dto.BooleanObject;
|
||||
|
||||
@RestController
|
||||
public class ValidationController {
|
||||
|
||||
@PostMapping("/validateBoolean")
|
||||
public ResponseEntity<String> addUser(@RequestBody @Valid BooleanObject booleanObj) {
|
||||
return ResponseEntity.ok("BooleanObject is valid");
|
||||
}
|
||||
}
|
|
@ -0,0 +1,37 @@
|
|||
package com.baeldung.controlleradvice;
|
||||
|
||||
import java.util.stream.Collectors;
|
||||
|
||||
import org.springframework.http.HttpStatus;
|
||||
import org.springframework.web.bind.MethodArgumentNotValidException;
|
||||
import org.springframework.web.bind.annotation.ExceptionHandler;
|
||||
import org.springframework.web.bind.annotation.ResponseStatus;
|
||||
import org.springframework.web.bind.annotation.RestControllerAdvice;
|
||||
|
||||
import com.fasterxml.jackson.databind.exc.InvalidFormatException;
|
||||
|
||||
@RestControllerAdvice
|
||||
public class GlobalExceptionHandler {
|
||||
|
||||
@ExceptionHandler(MethodArgumentNotValidException.class)
|
||||
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
|
||||
public String handleValidationException(MethodArgumentNotValidException ex) {
|
||||
return ex.getBindingResult()
|
||||
.getFieldErrors()
|
||||
.stream()
|
||||
.map(e -> e.getDefaultMessage())
|
||||
.collect(Collectors.joining(","));
|
||||
}
|
||||
|
||||
@ExceptionHandler(IllegalArgumentException.class)
|
||||
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
|
||||
public String handleIllegalArugmentException(IllegalArgumentException ex) {
|
||||
return ex.getMessage();
|
||||
}
|
||||
|
||||
@ExceptionHandler(InvalidFormatException.class)
|
||||
@ResponseStatus(value = HttpStatus.BAD_REQUEST)
|
||||
public String handleInvalidFormatException(InvalidFormatException ex) {
|
||||
return ex.getOriginalMessage();
|
||||
}
|
||||
}
|
|
@ -0,0 +1,18 @@
|
|||
package com.baeldung.deserializer;
|
||||
|
||||
import java.io.IOException;
|
||||
|
||||
import com.fasterxml.jackson.core.JsonParser;
|
||||
import com.fasterxml.jackson.databind.DeserializationContext;
|
||||
import com.fasterxml.jackson.databind.JsonDeserializer;
|
||||
|
||||
public class BooleanDeserializer extends JsonDeserializer<Boolean> {
|
||||
@Override
|
||||
public Boolean deserialize(JsonParser p, DeserializationContext ctxt) throws IOException {
|
||||
String value = p.getText();
|
||||
if (value != null && !value.equals("TRUE") && !value.equals("FALSE")) {
|
||||
throw new IllegalArgumentException("Boolean value must come as Capital TRUE or FALSE");
|
||||
}
|
||||
return Boolean.valueOf(value);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,26 @@
|
|||
package com.baeldung.dto;
|
||||
|
||||
import javax.validation.constraints.AssertFalse;
|
||||
import javax.validation.constraints.AssertTrue;
|
||||
import javax.validation.constraints.NotNull;
|
||||
|
||||
import com.baeldung.deserializer.BooleanDeserializer;
|
||||
import com.fasterxml.jackson.databind.annotation.JsonDeserialize;
|
||||
|
||||
import lombok.Data;
|
||||
|
||||
@Data
|
||||
public class BooleanObject {
|
||||
|
||||
@NotNull(message = "boolField cannot be null")
|
||||
Boolean boolField;
|
||||
|
||||
@AssertTrue(message = "trueField must have true value")
|
||||
Boolean trueField;
|
||||
|
||||
@AssertFalse(message = "falseField must have false value")
|
||||
Boolean falseField;
|
||||
|
||||
@JsonDeserialize(using = BooleanDeserializer.class)
|
||||
Boolean boolStringVar;
|
||||
}
|
|
@ -0,0 +1,17 @@
|
|||
package com.baeldung.service;
|
||||
|
||||
import javax.validation.Valid;
|
||||
|
||||
import org.springframework.stereotype.Service;
|
||||
import org.springframework.validation.annotation.Validated;
|
||||
|
||||
import com.baeldung.dto.BooleanObject;
|
||||
|
||||
@Service
|
||||
@Validated
|
||||
public class ValidationService {
|
||||
|
||||
public void validateBoolean(@Valid BooleanObject booleanObj) {
|
||||
// further processing
|
||||
}
|
||||
}
|
|
@ -0,0 +1,104 @@
|
|||
package com.baeldung.controller;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post;
|
||||
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.autoconfigure.web.servlet.WebMvcTest;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
import org.springframework.test.web.servlet.MockMvc;
|
||||
|
||||
import com.baeldung.dto.BooleanObject;
|
||||
import com.fasterxml.jackson.databind.ObjectMapper;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@WebMvcTest(controllers = ValidationController.class)
|
||||
class ValidationControllerUnitTest {
|
||||
|
||||
@Autowired
|
||||
private ObjectMapper objectMapper;
|
||||
|
||||
@Autowired
|
||||
private MockMvc mockMvc;
|
||||
|
||||
@Test
|
||||
void testNullBoolean() throws Exception {
|
||||
BooleanObject boolObj = new BooleanObject();
|
||||
boolObj.setBoolField(null);
|
||||
String postBody = objectMapper.writeValueAsString(boolObj);
|
||||
|
||||
mockMvc.perform(post("/validateBoolean").contentType("application/json")
|
||||
.content(postBody))
|
||||
.andExpect(status().isBadRequest());
|
||||
|
||||
}
|
||||
|
||||
@Test
|
||||
void testTrueBoolean() throws Exception {
|
||||
BooleanObject boolObj = new BooleanObject();
|
||||
boolObj.setBoolField(Boolean.TRUE);
|
||||
boolObj.setTrueField(Boolean.FALSE);
|
||||
String postBody = objectMapper.writeValueAsString(boolObj);
|
||||
|
||||
String output = mockMvc.perform(post("/validateBoolean").contentType("application/json")
|
||||
.content(postBody))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
assertEquals("trueField must have true value", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testFalseBoolean() throws Exception {
|
||||
BooleanObject boolObj = new BooleanObject();
|
||||
boolObj.setBoolField(Boolean.TRUE);
|
||||
boolObj.setTrueField(Boolean.TRUE);
|
||||
boolObj.setFalseField(Boolean.TRUE);
|
||||
String postBody = objectMapper.writeValueAsString(boolObj);
|
||||
|
||||
String output = mockMvc.perform(post("/validateBoolean").contentType("application/json")
|
||||
.content(postBody))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
assertEquals("falseField must have false value", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBooleanFromString() throws Exception {
|
||||
BooleanObject boolObj = new BooleanObject();
|
||||
boolObj.setBoolField(Boolean.TRUE);
|
||||
boolObj.setTrueField(Boolean.TRUE);
|
||||
boolObj.setFalseField(Boolean.FALSE);
|
||||
boolObj.setBoolStringVar(true);
|
||||
String postBody = objectMapper.writeValueAsString(boolObj);
|
||||
|
||||
String output = mockMvc.perform(post("/validateBoolean").contentType("application/json")
|
||||
.content(postBody))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
assertEquals("Boolean value must come as Capital TRUE or FALSE", output);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testValidBean() throws Exception {
|
||||
|
||||
String postBody = "{\"boolField\":true,\"trueField\":true,\"falseField\":false,\"boolStringVar\":\"TRUE\"}";
|
||||
|
||||
String output = mockMvc.perform(post("/validateBoolean").contentType("application/json")
|
||||
.content(postBody))
|
||||
.andReturn()
|
||||
.getResponse()
|
||||
.getContentAsString();
|
||||
|
||||
assertEquals("BooleanObject is valid", output);
|
||||
|
||||
}
|
||||
}
|
|
@ -0,0 +1,28 @@
|
|||
package com.baeldung.dto;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.assertEquals;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
|
||||
class BooleanUnitTest {
|
||||
|
||||
@Test
|
||||
void testBooleanFromString() {
|
||||
Boolean trueVar = Boolean.valueOf("TRUE");
|
||||
Boolean falseVar = Boolean.valueOf("false");
|
||||
Boolean parsedVar = Boolean.parseBoolean("True");
|
||||
|
||||
assertEquals(Boolean.TRUE, trueVar);
|
||||
assertEquals(Boolean.FALSE, falseVar);
|
||||
assertEquals(Boolean.TRUE, parsedVar);
|
||||
}
|
||||
|
||||
@Test
|
||||
void testBoolean() {
|
||||
Boolean trueVar = Boolean.valueOf(true);
|
||||
Boolean falseVar = Boolean.valueOf(false);
|
||||
|
||||
assertEquals(Boolean.TRUE, trueVar);
|
||||
assertEquals(Boolean.FALSE, falseVar);
|
||||
}
|
||||
}
|
|
@ -0,0 +1,35 @@
|
|||
package com.baeldung.service;
|
||||
|
||||
import static org.junit.Assert.assertTrue;
|
||||
import static org.junit.jupiter.api.Assertions.assertThrows;
|
||||
|
||||
import javax.validation.ConstraintViolationException;
|
||||
|
||||
import org.junit.jupiter.api.Test;
|
||||
import org.junit.jupiter.api.extension.ExtendWith;
|
||||
import org.springframework.beans.factory.annotation.Autowired;
|
||||
import org.springframework.boot.test.context.SpringBootTest;
|
||||
import org.springframework.test.context.junit.jupiter.SpringExtension;
|
||||
|
||||
import com.baeldung.dto.BooleanObject;
|
||||
|
||||
@ExtendWith(SpringExtension.class)
|
||||
@SpringBootTest
|
||||
class ValidationServiceUnitTest {
|
||||
|
||||
@Autowired
|
||||
ValidationService service;
|
||||
|
||||
@Test
|
||||
void validateBoolean() {
|
||||
BooleanObject boolObj = new BooleanObject();
|
||||
boolObj.setBoolField(Boolean.valueOf(true));
|
||||
boolObj.setTrueField(Boolean.FALSE);
|
||||
Throwable throwableError = assertThrows(ConstraintViolationException.class, () -> {
|
||||
service.validateBoolean(boolObj);
|
||||
});
|
||||
assertTrue(throwableError.getLocalizedMessage()
|
||||
.endsWith("trueField must have true value"));
|
||||
}
|
||||
|
||||
}
|
Loading…
Reference in New Issue