admin管理员组文章数量:1405170
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?
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?
Share Improve this question edited Mar 19 at 18:18 Geba 2,23111 silver badges16 bronze badges asked Mar 8 at 19:50 Peter PenzovPeter Penzov 1,630156 gold badges501 silver badges908 bronze badges 4 |1 Answer
Reset to default 2 +100The 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.
本文标签:
版权声明:本文标题:mockito - Cannot invoke "java.lang.reflect.Method.getDeclaringClass()" because "method" is n 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744886619a2630525.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
Cannot subclass final class java.lang.reflect.Method
(fixed by using togetLastInvocationAware
) – Geba Commented Mar 19 at 8:58