From 1cdb01b6d46f47420a81d822594fe5e37406c337 Mon Sep 17 00:00:00 2001 From: Michael Hoennig Date: Mon, 9 Dec 2024 15:56:50 +0100 Subject: [PATCH] add missing Validate.java + Test --- .../hsadminng/errors/Validate.java | 23 ++++++++++++++ .../hsadminng/errors/ValidateUnitTest.java | 31 +++++++++++++++++++ 2 files changed, 54 insertions(+) create mode 100644 src/main/java/net/hostsharing/hsadminng/errors/Validate.java create mode 100644 src/test/java/net/hostsharing/hsadminng/errors/ValidateUnitTest.java diff --git a/src/main/java/net/hostsharing/hsadminng/errors/Validate.java b/src/main/java/net/hostsharing/hsadminng/errors/Validate.java new file mode 100644 index 00000000..3ce68fe9 --- /dev/null +++ b/src/main/java/net/hostsharing/hsadminng/errors/Validate.java @@ -0,0 +1,23 @@ +package net.hostsharing.hsadminng.errors; + +import lombok.AllArgsConstructor; + +import jakarta.validation.ValidationException; + +@AllArgsConstructor +public class Validate { + + final String variableNames; + + public static Validate validate(final String variableNames) { + return new Validate(variableNames); + } + + public final void atMaxOneNonNull(final Object var1, final Object var2) { + if (var1 != null && var2 != null) { + throw new ValidationException( + "Exactly one of (" + variableNames + ") must be non-null, " + + "but are (" + var1 + ", " + var2 + ")"); + } + } +} diff --git a/src/test/java/net/hostsharing/hsadminng/errors/ValidateUnitTest.java b/src/test/java/net/hostsharing/hsadminng/errors/ValidateUnitTest.java new file mode 100644 index 00000000..0d212c90 --- /dev/null +++ b/src/test/java/net/hostsharing/hsadminng/errors/ValidateUnitTest.java @@ -0,0 +1,31 @@ +package net.hostsharing.hsadminng.errors; + +import org.junit.jupiter.api.Test; + +import jakarta.validation.ValidationException; + +import static org.assertj.core.api.Assertions.assertThat; +import static org.assertj.core.api.Assertions.catchThrowable; + +class ValidateUnitTest { + + @Test + void shouldFailValidationIfBothParametersAreNotNull() { + final var throwable = catchThrowable(() -> + Validate.validate("var1, var2").atMaxOneNonNull("val1", "val2") + ); + assertThat(throwable).isInstanceOf(ValidationException.class) + .hasMessage("Exactly one of (var1, var2) must be non-null, but are (val1, val2)"); + } + + @Test + void shouldNotFailValidationIfBothParametersAreull() { + Validate.validate("var1, var2").atMaxOneNonNull(null, null); + } + + @Test + void shouldNotFailValidationIfExactlyOneParameterIsNonNull() { + Validate.validate("var1, var2").atMaxOneNonNull("val1", null); + Validate.validate("var1, var2").atMaxOneNonNull(null, "val2"); + } +}