|
| 1 | +/* |
| 2 | + * Copyright 2012-2025 the original author or authors. |
| 3 | + * |
| 4 | + * Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 | + * you may not use this file except in compliance with the License. |
| 6 | + * You may obtain a copy of the License at |
| 7 | + * |
| 8 | + * https://www.apache.org/licenses/LICENSE-2.0 |
| 9 | + * |
| 10 | + * Unless required by applicable law or agreed to in writing, software |
| 11 | + * distributed under the License is distributed on an "AS IS" BASIS, |
| 12 | + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 | + * See the License for the specific language governing permissions and |
| 14 | + * limitations under the License. |
| 15 | + */ |
| 16 | +package org.springframework.data.mongodb.core.mapping.event; |
| 17 | + |
| 18 | +import static org.assertj.core.api.Assertions.assertThat; |
| 19 | +import static org.assertj.core.api.Assertions.assertThatExceptionOfType; |
| 20 | + |
| 21 | +import jakarta.validation.ConstraintViolationException; |
| 22 | +import jakarta.validation.Validation; |
| 23 | +import jakarta.validation.ValidatorFactory; |
| 24 | +import jakarta.validation.constraints.Min; |
| 25 | +import jakarta.validation.constraints.NotNull; |
| 26 | +import org.bson.Document; |
| 27 | +import org.junit.jupiter.api.BeforeEach; |
| 28 | +import org.junit.jupiter.api.Test; |
| 29 | + |
| 30 | +/** |
| 31 | + * Unit test for {@link ValidatingEntityCallback}. |
| 32 | + * |
| 33 | + * @author Rene Felgenträger |
| 34 | + */ |
| 35 | +class ValidatingEntityCallbackTests { |
| 36 | + |
| 37 | + private ValidatingEntityCallback callback; |
| 38 | + |
| 39 | + @BeforeEach |
| 40 | + public void setUp() { |
| 41 | + try (ValidatorFactory factory = Validation.buildDefaultValidatorFactory()) { |
| 42 | + callback = new ValidatingEntityCallback(factory.getValidator()); |
| 43 | + } |
| 44 | + } |
| 45 | + |
| 46 | + @Test |
| 47 | + void invalidModel_throwsException() { |
| 48 | + Coordinates coordinates = new Coordinates(-1, -1); |
| 49 | + |
| 50 | + assertThatExceptionOfType(ConstraintViolationException.class) |
| 51 | + .isThrownBy(() -> callback.onBeforeSave(coordinates, coordinates.toDocument(), "coordinates")) |
| 52 | + .satisfies(e -> assertThat(e.getConstraintViolations()).hasSize(2)); |
| 53 | + } |
| 54 | + |
| 55 | + @Test |
| 56 | + void validModel_noException() { |
| 57 | + Coordinates coordinates = new Coordinates(0, 0); |
| 58 | + Object entity = callback.onBeforeSave(coordinates, coordinates.toDocument(), "coordinates"); |
| 59 | + assertThat(entity).isEqualTo(coordinates); |
| 60 | + } |
| 61 | + |
| 62 | + record Coordinates(@NotNull @Min(0) Integer x, @NotNull @Min(0) Integer y) { |
| 63 | + |
| 64 | + Document toDocument() { |
| 65 | + return Document.parse(""" |
| 66 | + { |
| 67 | + "x": %d, |
| 68 | + "y": %d |
| 69 | + } |
| 70 | + """.formatted(x, y)); |
| 71 | + } |
| 72 | + } |
| 73 | +} |
0 commit comments