Dark theme | Light theme

July 5, 2023

Awesome AssertJ: Check Base64 Encoded Strings

AssertJ has some nice methods to verify string values. If we want to verify a string value is Base64 encoded we can use the isBase64String() method. We can leave out the padding of the value as it is optional. With the method asBase64Decoded() we can decode the value and write our assertions for the decoded value. The method asBase64Decoded() returns a byte[] object and we can use the asString() to convert it into a string value again.

In the following example we use the isBase64() and asBase64Decoded() methods:

package mrhaki;

import org.junit.jupiter.api.Test;

import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatExceptionOfType;

public class StringBase64 {

    void checkValueIsBase64Encoded() {
        // We can simply check if the value is Base64 encoded
        // with the method isBase64().

        // Padding (=) can be omitted from the Base64 encoded value.

        // If we want to check a value is NOT Base64 encoded we
        // need to check an AssertionError is thrown.
                .isThrownBy(() -> assertThat("AssertJ is Awesome").isBase64())
                .withMessageContaining("Expecting \"AssertJ is Awesome\" to be a valid Base64 encoded string");

    void checkBase64EncodedValue() {
        // We can use asBase64Decoded() to get a byte[] result
        // and apply our assertions.
                .isEqualTo("AssertJ be Awesome, matey!");

        // Also here the padding (=) can be omitted.
                .isEqualTo("AssertJ be Awesome, matey!");

                .isNotEqualTo("AssertJ is Awesome!");

Written with AssertJ 3.24.2.