I want to mock a complex case of Java method response into JUnit 5 test which is using hateoas.
The JUnit 5 test:
@ExtendWith(MockitoExtension.class)
public class ReportingATest {
@Spy
protected StaticPathLinkBuilder staticPathLinkBuilder =
new StaticPathLinkBuilder(UriComponentsBuilder.fromHttpUrl("http://localhost"));
@Test
public void testSuccessfully() throws NoSuchMethodException {
// Stub with the real method
when(staticPathLinkBuilder.linkTo(any(), any()))
.thenReturn(mock(LinkBuilder.class));
ReportingResource reportingResource = reportingAssembler.mergeReturnReversal(returnReversalReport,
this.reportingResource);
assertNotNull(reportingResource.getReturnReversal());
}
}
mergeReturnReversal
calls :
Link link = staticPathLinkBuilder.linkTo(
methodOn(ReturnReversalController.class).getReturnReversalById(
returnReversalReport.getAccount().getId(),
returnReversalReport.getReturnReversal().getId())
).withSelfRel();
staticPathLinkBuilder
is instance of StaticPathLinkBuilder
:
public class StaticPathLinkBuilder extends LinkBuilderSupport<StaticPathLinkBuilder> {
private static final AnnotationMappingDiscoverer ANNOTATION_MAPPING_DISCOVERER =
new AnnotationMappingDiscoverer(RequestMapping.class);
public StaticPathLinkBuilder(UriComponentsBuilder builder) {
super(builder.build());
}
public LinkBuilder linkTo(Method method, Object... parameters) {
URI relativeUri = createRelativeUri(method, parameters);
return slash(UriComponentsBuilder.fromUri(relativeUri).build(), true);
}
private URI createRelativeUri(Method method, Object... parameters) {
String mapping = ANNOTATION_MAPPING_DISCOVERER.getMapping(method.getDeclaringClass(), method);
UriTemplate template = new UriTemplate(mapping);
return template.expand(parameters);
}
public LinkBuilder linkTo(Object dummyInvocation) {
if (!(dummyInvocation instanceof LastInvocationAware)) {
IllegalArgumentException cause =
new IllegalArgumentException("linkTo(Object) must be call with a dummyInvocation");
throw InternalErrorException.builder()
.cause(cause)
.build();
}
LastInvocationAware lastInvocationAware = (LastInvocationAware) dummyInvocation;
MethodInvocation methodInvocation = lastInvocationAware.getLastInvocation();
StaticPathLinkBuilder staticPathLinkBuilder = getThis();
return staticPathLinkBuilder.linkTo(methodInvocation.getMethod(), methodInvocation.getArguments());
}
}
When I run testSuccessfully
, ANNOTATION_MAPPING_DISCOVERER.getMapping(method.getDeclaringClass(), method)
throws an exception:
Cannot invoke "java.lang.reflect.Method.getDeclaringClass()" because "method" is null
java.lang.NullPointerException: Cannot invoke "java.lang.reflect.Method.getDeclaringClass()" because "method" is null
at com.util.StaticPathLinkBuilder.createRelativeUri(StaticPathLinkBuilder.java:74)
What is the proper way to mock the code so that the JUnit test should pass?
The exception is thrown because the real method LinkBuilder linkTo(Method method, Object... parameters)
is called with any()
as method
and any()
resolves to null
.
The stubbing, that you have, works if you are stubbing a method of a Mock
:
when(staticPathLinkBuilder.linkTo(any(), any()))
.thenReturn(mock(LinkBuilder.class));
But staticPathLinkBuilder
is not a Mock
, it is a Spy
.
The stubbing, that you have, for Spy
leads to the real method execution, which leads to the exception.
To stub a Spy
's method, use the following approach instead:
doReturn(mock(LinkBuilder.class))
.when(staticPathLinkBuilder)
.linkTo(any(), any());
This should resolve the exception.
Solution provided after the repository link was shared.
The exception is different because the code in the repository is not identical to the code in the original question.
Problem with the code from the repo:
You are using sensitive API, that is not intended for public use while it is public.
The library authors explain this in this GitHub issue.
They also suggest a workaround in the same github issue - use DummyInvocationUtils.getLastInvocationAware(...)
.
For your specific case, replace this:
LastInvocationAware lastInvocationAware = (LastInvocationAware) dummyInvocation;
with:
LastInvocationAware lastInvocationAware = DummyInvocationUtils.getLastInvocationAware(dummyInvocation);
Also you need to handle Unnecessary stubbings
:
when(returnReversalAssembler.fromReturnReversal(any(), any()))
.thenReturn(reportingReturnReversalResource);
So the tested code has to call the mocked method or you need to remove unnecessary stubbing.