baeldung-articles : BAEL-7442 (#15887)

* baeldung-articles : BAEL-7442

Check if String is Base64 Encoded (commit)

* Update CheckIfStringIsBased64UnitTest.java
This commit is contained in:
DiegoMarti2 2024-02-17 14:12:34 -08:00 committed by GitHub
parent 988d1640e0
commit 7cbf2eafcd
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194

View File

@ -0,0 +1,40 @@
package com.baeldung.checkifstringisbased64;
import org.junit.jupiter.api.Test;
import java.util.Base64;
import java.util.regex.Pattern;
import static org.junit.jupiter.api.Assertions.*;
public class CheckIfStringIsBased64UnitTest {
@Test
public void givenBase64EncodedString_whenDecoding_thenNoException() {
try {
Base64.getDecoder().decode("SGVsbG8gd29ybGQ=");
assertTrue(true);
} catch (IllegalArgumentException e) {
fail("Unexpected exception: " + e.getMessage());
}
}
@Test
public void givenNonBase64String_whenDecoding_thenCatchException() {
try {
Base64.getDecoder().decode("Hello world!");
fail("Expected IllegalArgumentException was not thrown");
} catch (IllegalArgumentException e) {
assertTrue(true);
}
}
@Test
public void givenString_whenOperatingRegex_thenCheckIfItIsBase64Encoded() {
Pattern BASE64_PATTERN = Pattern.compile(
"^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$"
);
assertTrue(BASE64_PATTERN.matcher("SGVsbG8gd29ybGQ=").matches());
}
}