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.

shadow-left