Search

Dark theme | Light theme
Showing posts with label AwesomeAssertJ:Strings. Show all posts
Showing posts with label AwesomeAssertJ:Strings. Show all posts

January 28, 2026

Awesome AssertJ: Use isEqualToNormalizingNewlines To Assert With Text Block

A Java text block is an easy way to have a multiline string value. But there is a catch if we want to use a text block with the assertion method isEqualTo. Suppose you have written a piece of code that create a new string value where the line endings are defined using System.lineSeparator(). The string value would have the line ending \n on Linux and MacOS systems, and the line ending \r\n on Windows system. But a Java text block will always use the line ending \n on every platform, including the Windows platform. If you would run your tests on a Windows platform then the assertion using isEqualTo will fail, but the test will pass on Linux or MacOS systems. This is a problem if you are working with developers using different operating systems. Therefore it is better to use the method isEqualToNormalizingNewlines for these type of assertions. AssertJ will make sure the line endings are the same and the tests will pass independent of the operating system the tests are run on.

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 {

    @Test
    void checkValueIsBase64Encoded() {
        // We can simply check if the value is Base64 encoded
        // with the method isBase64().
        assertThat("QXNzZXJ0SiBiZSBBd2Vzb21lLCBtYXRleSE=").isBase64();

        // Padding (=) can be omitted from the Base64 encoded value.
        assertThat("QXNzZXJ0SiBiZSBBd2Vzb21lLCBtYXRleSE").isBase64();

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

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

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

        assertThat("QXNzZXJ0SiBiZSBBd2Vzb21lLCBtYXRleSE=")
                .asBase64Decoded().asString()
                .isNotEqualTo("AssertJ is Awesome!");
    }
}

Written with AssertJ 3.24.2.

Awesome AssertJ: Use String Template To Verify String Value

To compare string values we can use the isEqualTo(String) method in AssertJ. But if we want to verify that a string contains a certain variable value we can use string templates. This makes the assertion more readable as we can see what value we expect in the string. To use string templates we must the method isEqualTo(String, Object…​). The first argument is the string template and the following arguments will be the actual values that should be used in the template. Actually the String.format(String, Object…​) method is used behind the scenes to format the string template, but we don’t have to clutter our assertions with that call.

In the following example we see how we can use string templates to verify string values:

package mrhaki;

import org.junit.jupiter.api.Test;
import org.junit.jupiter.params.ParameterizedTest;
import org.junit.jupiter.params.provider.ValueSource;

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

public class StringIsEqualToTemplate {

    @Test
    void verifyStringIsEqualTo() {
        // We can use a template to define the format of the String.
        // If we do actually String.format() is used to create
        // our expected value.
        assertThat("AssertJ is awesome!").isEqualTo("%s is %s!", "AssertJ", "awesome");
    }

    // Using a template can be very useful for example in parameterized tests.
    @ParameterizedTest
    @ValueSource(strings = {"AssertJ", "Spock"})
    void verifyStringFormat(String libraryName) {
        // given
        record Library(String name) {
            @Override
            public String toString() {
                return name;
            }
        }
        var library = new Library(libraryName);

        // expect
        assertThat(library.name() + " is awesome").isEqualTo("%s is awesome", library);
    }

    @Test
    void verifyStringIsNotEqualTo() {
        // There is no method implementation for isNotEqualTo where we can define
        // the format as first argument. But we can still use String.format
        // ourselves to achieve the same functionality.
        assertThat("AssertJ is awesome!").isNotEqualTo(String.format("%s is %s!", "Spock", "awesome"));
    }
}

Written with AssertJ 3.24.2.

June 30, 2023

Awesome AssertJ: Check String Starts Or Ends With A Given Value

Writing assertions using the nice fluent API of AssertJ is a joy. Besides some of the basic assertions like isEqualTo AssertJ also has specific assertions for specific types. For example if we want write an assertion to check if a String value starts or ends with an expected value we can use the startsWith(String) or endsWith(String) methods. If we don’t care that a character is upper or lower case we can also use startsWithIgnoringCase(String) or endsWithIgnoringCase(String). Each of the methods also has a counterpart method to check the String value doesn’t start or end with an expected value. For example we can use doesNotStartWith(String) to assert a value does not start with the expected value.

Instead of using the specific startsWith…​(String) or endsWith…​(String) methods we can also use the more generic matches method. Now we need to specify a Pattern or Predicate that matches our requirement. This give some more flexbility but is also more verbose. To test there is not a match we can use the doesNotMatch method.

In the following example we write assertions to check if a String value starts with an expected value:

package mrhaki;

import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;

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

class StringStartsWith {

    @Test
    void testStringStartsWith() {
        assertThat("Awesome AssertJ").startsWith("Awesome");

        // We can also check ignoring the casing of the String value.
        assertThat("Awesome AssertJ").startsWithIgnoringCase("aweSome");
    }

    @Test
    void testStringDoesNotStartWith() {
        // Or we check a String value doesn't start with an expected value.
        assertThat("Amazing Assertj").doesNotStartWith("Awesome");

        // We can also check ignoring the casing of the String value.
        assertThat("Amazing Assertj").doesNotStartWithIgnoringCase("aweSome");
    }

    @Test
    void testStringStartsWithRegex() {
        // We can use regular expressions as well, but it is more verbose.
        assertThat("Awesome AssertJ").matches(Pattern.compile("^Awesome.*"));

        // Also here we can ignore casing.
        assertThat("Awesome AssertJ").matches(Pattern.compile("^awesome.*", Pattern.CASE_INSENSITIVE));

        // And check String value doesn't start with expected value.
        assertThat("Amazing AssertJ").doesNotMatch(Pattern.compile("^Awesome.*"));
    }

    @Test
    void testStringStartsWithPredicate() {
        // We can use a Predicate as well, but it is more verbose.
        assertThat("Awesome AssertJ").matches(s -> s.startsWith("Awesome"));

        // We are more flexible as we can use for example specify an offset.
        assertThat("Awesome AssertJ").matches(s -> s.startsWith("some", 3));

        // If we want to ignore casing we have to first convert our value.
        assertThat("Awesome AssertJ").matches(s -> s.toLowerCase().startsWith("awesome"));

        // And check String value doesn't start with expected value.
        assertThat("Amazing AssertJ").matches(s -> !s.startsWith("Awesome"));
    }
}

And in the next example we write assertions to check if a String value ends with an expected value:

package mrhaki;

import org.junit.jupiter.api.Test;
import java.util.regex.Pattern;

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

class StringEndsWith {

    @Test
    void testStringEndsWith() {
        assertThat("Awesome AssertJ").endsWith("AssertJ");

        // We can also check ignoring the casing of the String value.
        assertThat("Awesome AssertJ").endsWithIgnoringCase("assertJ");
    }

    @Test
    void testStringDoesNotEndWith() {
        // Or we we check our String values doesn't end with an expected value.
        assertThat("Awesome Asciidoc").doesNotEndWith("AssertJ");

        // We can also check ignoring the casing of the String value.
        assertThat("Awesome Asciidoc").doesNotEndWithIgnoringCase("assertJ");
    }

    @Test
    void testStringEndsWithRegex() {
        // We can use regular expressions as well, but it is more verbose.
        assertThat("Awesome AssertJ").matches(Pattern.compile(".*AssertJ$"));

        // Also here we can ignore casing.
        assertThat("Awesome AssertJ").matches(Pattern.compile(".*AssertJ$", Pattern.CASE_INSENSITIVE));

        // And check String value doesn't end with expected value.
        assertThat("Amazing Asciidoc").doesNotMatch(Pattern.compile(".*AssertJ$"));
    }

    @Test
    void testStringEndsWithPredicate() {
        // We can use a Predicate as well, but it is more verbose.
        assertThat("Awesome AssertJ").matches(s -> s.endsWith("AssertJ"));

        // If we want to ignore casing we have to first convert our value.
        assertThat("Awesome AssertJ").matches(s -> s.toLowerCase().endsWith("assertj"));

        // And check String value doesn't end with expected value.
        assertThat("Awesome Asciidoc").matches(s -> !s.endsWith("AssertJ"));
    }
}

Written with AssertJ 3.24.2.

June 29, 2023

Awesome AssertJ: Assert toString Method of Object With hasToString Method

AssertJ has many useful methods to write assertions using a fluid API. If we want to test the toString() method implementation of an object we can of course invoke the toString() method inside an assertThat expression and check with the assert method isEqualTo(String) the value. But AssertJ can make that easier so we don’t have to invoke toString() method ourselves. We can use the assert method hasToString(String) on the object we defined in the assertThat expression and specify our expected value as argument to the method. If we want to assert the toString() method doesn’t return an expected value we can use the assert method doesNotHaveToString(String).

In the following example test we use the methods hasToString and doesNotHaveToString for different

package mrhaki;

import org.junit.jupiter.api.Test;

import java.util.List;
import java.util.Map;

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

class HasToString {

    // Helper class used in tests to check toString().
    private static class User {
        private final String username;

        public User(String username) {
            this.username = username;
        }

        public String toString() {
            return String.format("[User{username=%s}]", username);
        }
    }

    @Test
    void testHasToString() {
        // We can assert the toString() method of arbitrary objects
        // with hasToString(String).
        assertThat(new User("mrhaki")).hasToString("[User{username=mrhaki}]");
    }

    @Test
    void testDoesNotHaveString() {
        // If we want to assert the toString() method doesn't return a value
        // we can use doesNotHaveToString(String).
        assertThat(new User("mrhaki")).doesNotHaveToString("User[user=mrhaki]");
    }

    @Test
    void testIntegerToString() {
        // Simple types are automatically boxed to the object wrapper type
        // and then have a toString() method to assert the value for.
        assertThat(42).hasToString("42");  // int value is boxed to Integer.
        assertThat(Integer.valueOf(42)).hasToString("42");
    }

    @Test
    void testListToString() {
        // We can test toString() on List instances.
        var items = List.of("TDD", "JUnit", "AssertJ");
        assertThat(items).hasToString("[TDD, JUnit, AssertJ]");
        assertThat(items).doesNotHaveToString("[TDD,JUnit,AssertJ");
    }

    @Test
    void testMapToString() {
        // We can test toString() on Map instances.
        var map = Map.of("language", "Java");
        assertThat(map).hasToString("{language=Java}");
        assertThat(map).doesNotHaveToString("[language:Java]");
    }
}

Written with AssertJ 3.24.2.