add missing Validate.java + Test

This commit is contained in:
Michael Hoennig 2024-12-09 15:56:50 +01:00
parent 04bb9aa206
commit 1cdb01b6d4
2 changed files with 54 additions and 0 deletions

View File

@ -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 + ")");
}
}
}

View File

@ -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");
}
}