Verify passing a method reference

683 views
Skip to first unread message

Vito De Tullio

unread,
May 21, 2020, 10:11:43 AM5/21/20
to mockito
Hi.
I have this setup (simplified):

import java.util.function.Function;

public class Foo {
    Bar bar;

    void myMethod() {
        final Function<String, String> reference;
        if (...)
            reference = String::toLowerCase;
        else
            reference = String::toUpperCase;

        this.bar.otherMethod(reference);
    }
}

class Bar {
    void otherMethod(final Function<String, String> transform) {
        /* ... */
    }
}

I would like to verify the "myMethod" behavior.

I have tried to mock the `bar` instance, call the `myMethod` method and `verify(bar).otherMethod(expectedReference)`

Unfortunately this approach fails, mostly because - as described in https://stackoverflow.com/a/38963341/273593 - the method reference is compiled to a new instance of an anonimous class.

Is there some other way to check that the correct reference has been passed to `bar.otherMethod(...)`?
Keep in mind that myMethod doesn't call the reference itself (nor the `otherMethod`... the variable is passed around for 2-3 nested calls).

Thanks

Vito De Tullio

unread,
May 28, 2020, 7:00:07 AM5/28/20
to mockito
Reply all
Reply to author
Forward
0 new messages