Skip to content

Add name parameter to argThat #1932

@ST-DDT

Description

@ST-DDT

Argument matchers that are created with argThat using lambdas create an unreadable output, that does not really help:

    @Test
    void test() {
        Consumer c = mock(Consumer.class);
        c.accept(null);
        verify(c, never()).accept(argThat(arg -> arg == null)); // <-- complex check here
    }
org.mockito.exceptions.verification.NeverWantedButInvoked: 
consumer.accept(
    <Test$$ lambda$ 5 4 4/ 0x 0 0 0 0 0 0 0 8 0 0 5eb 8 4 0>
);
Never wanted here:
-> at com.example.Test.test(Test.java:1077)
But invoked here:
-> at com.example.Test.test(Test.java:1076)

	at com.example.Test.test(Test.java:1077)

I searched a bit in the internet whether it is possible to somehow get a useful name for lambdas, but that doesn't seem to be possible. So instead, I would like to have an argThat method with an additional name (or description or message) parameter.

Example:

    @Test
    void test() {
        Consumer c = mock(Consumer.class);
        c.accept(null);
        verify(c, never()).accept(argThat("is null", arg -> arg == null));
    }
org.mockito.exceptions.verification.NeverWantedButInvoked: 
consumer.accept(
    "is null"
);
Never wanted here:
-> at com.example.Test.test(Test.java:1077)
But invoked here:
-> at com.example.Test.test(Test.java:1076)

	at com.example.Test.test(Test.java:1077)

This is already possible right now, but needs to be copied for every project:

public static <T> T namedArgThat(final String name, final ArgumentMatcher<T> matcher) {
        return argThat(new ArgumentMatcher<>() {
            @Override
            public boolean matches(final T argument) {
                return matcher.matches(argument);
            }

            @Override
            public String toString() {
                return name;
            }
        });
    }

It would be nice if such a method could be added to the library itself.
The method is intended to be used with lambda expressions only.

As an alternative a static ArgumentMatcher#named(String, ArgumentMatcher) would work as well. Maybe this is even more useful, as it can be used for nested matchers as well.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions