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).
You could mock Bar and use an ArgumentCaptor to capture the value passed to the otherMethod and then assert that it's the expected reference. A simple test class may look like this (imports omitted for brevity):
@RunWith(MockitoJUnitRunner.class)
class MyTest {
@Mock
private Bar bar;
@InjectMocks
private Foo foo;
@Captor
private ArgumentCaptor<Function<String, String>> captor;
@Test
public void test() {
// insert your arguments here if you have any
foo.myMethod();
// verify bar is called and capture the method reference
verify(bar).otherMethod(captor.capture());
Function<String, String> transform = captor.getValue();
// do some assertions here, just checking that String::toLowerCase was used
// you may change this to fit your needs
Assert.assertEquals("somevalue", transform.apply("SomEvALuE"));
}
}
The whole snippet above is simplified of course, because you provided a simplified example. Also: you may not be able to use @InjectMocks because you need to inject Bar via another way into Foo.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With