NullPointerException for Mockito.spy when trying to mock an object that being created inside a method

huangapple go评论116阅读模式
英文:

NullPointerException for Mockito.spy when trying to mock an object that being created inside a method

问题

Helllo, I'm trying to write a test for my apply function. What I wanna do is to verify that the methods in the try catch scope are being called when executing the function. hhere is my apply method:

  1. public Target apply(Source source) throws MappingException {
  2. try {
  3. Target target = targetModelObjectFactory.create(Target.class);
  4. // ... (other method calls)
  5. return target;
  6. } catch (Exception e) {
  7. throw new MappingException(source, e);
  8. }
  9. }

here is my test for mapMailToEMail(source, target);

  1. @Test
  2. public void TestSettingMappedMailFromSourceToTargetEMail() {
  3. Source mockedSource = Mockito.mock(Source.class);
  4. Target mockedTarget = Mockito.mock(Target.class);
  5. sourceToTargetMapper.mapMailToEMail(mockedSource, mockedTarget);
  6. Mockito.verify(mockedTarget, Mockito.times(1)).setEMail(mockedSource.getMail());
  7. }

And here is a part of my test:

  1. @Test
  2. public void TestApply() throws MappingException, MappingOperatorCreationException, TargetModelObjectCreationException {
  3. Source mockedSource = Mockito.mock(Source.class);
  4. TargetModelObjectFactory targetModelObjectFactory = Mockito.mock(TargetModelObjectFactory.class);
  5. Target mockedTarget = Mockito.spy(targetModelObjectFactory.create(Target.class));
  6. sourceToTargetMapper.mapNameToFirstName(mockedSource, mockedTarget);
  7. Mockito.verify(mockedSource, Mockito.times(1)).setMail(mockedSource.getMail());
  8. }

The problem that I'm having is with this part

  1. Target target = targetModelObjectFactory.create(Target.class);

In my test I need to mock the Target object that being created inside the method, I was trying to use mockito.spy for this. But I keep on getting NullPointerException for it..

Is it the right approach?
What is it that I'm missing?
Any help would be appreciated

EDIT stackTrace

  1. java.lang.NullPointerException
  2. at org.mockito.Mockito.spy(Mockito.java:2034)
  3. at app.transcriber.example.generated.SourceToTargetMapperTest.TestApply(SourceToTargetMapperTest.java:87)
  4. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  5. // ... (remaining stack trace)

app.transcriber.example.generated.SourceToTargetMapperTest > TestApply FAILED
java.lang.NullPointerException at SourceToTargetMapperTest.java:87
1 test completed, 1 failed

英文:

Helllo, I'm trying to write a test for my apply function. What I wanna do is to verify that the methods
in the try catch scope are being called when executing the function.
hhere is my apply method:

  1. public Target apply(Source source) throws MappingException {
  2. try {
  3. Target target = targetModelObjectFactory.create(Target.class);
  4. mapNameToFirstName(source, target);
  5. mapMailToEMail(source, target);
  6. mapSourceSubEntityToTargetSubEntity(source, target);
  7. mapPrimitiveSourceColToPrimitiveTargetCol(source, target);
  8. mapSubEntitiesSourceColToSubEntitiesTargetCol(source, target);
  9. mapSourceSubEntityFieldToSubEntityFetchedField(source, target);
  10. produceProducedFieldValue(target);
  11. setConstantFieldConstantValue(target);
  12. return target;
  13. } catch (Exception e) {
  14. throw new MappingException(source, e);
  15. }
  16. }

here is my test for mapMailToEMail(source, target);

  1. @Test
  2. public void TestSettingMappedMailFromSourceToTargetEMail() {
  3. Source mockedSource = Mockito.mock(Source.class);
  4. Target mockedTarget = Mockito.mock(Target.class);
  5. sourceToTargetMapper.mapMailToEMail(mockedSource, mockedTarget);
  6. Mockito.verify(mockedTarget, Mockito.times(1)).setEMail(mockedSource.getMail());
  7. }

And here is a part of my test:

  1. @Test
  2. public void TestApply() throws MappingException, MappingOperatorCreationException, TargetModelObjectCreationException {
  3. Source mockedSource = Mockito.mock(Source.class);
  4. TargetModelObjectFactory targetModelObjectFactory = Mockito.mock(TargetModelObjectFactory.class)
  5. Target mockedTarget = Mockito.spy(targetModelObjectFactory.create(Target.class));
  6. sourceToTargetMapper.mapNameToFirstName(mockedSource,mockedTarget);
  7. Mockito.verify(mockedSource,Mockito.times(1)).setMail(mockedSource.getMail());
  8. }

The problem that I'm having is with this part

  1. Target target = targetModelObjectFactory.create(Target.class);

In my test I need to mock the Target object that being created inside the method, I was tryinh to use mockito.spy for this. But I keep on getting NullPointerException for it..

Is it the right approach?
What is is that I'm missing?
Any help would be appreciated

EDIT stackTrace

  1. java.lang.NullPointerException
  2. at org.mockito.Mockito.spy(Mockito.java:2034)
  3. at app.transcriber.example.generated.SourceToTargetMapperTest.TestApply(SourceToTargetMapperTest.java:87)
  4. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  5. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  6. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  7. at java.base/java.lang.reflect.Method.invoke(Method.java:564)
  8. at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
  9. at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
  10. at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
  11. at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
  12. at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
  13. at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54)
  14. at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
  15. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
  16. at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
  17. at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
  18. at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
  19. at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
  20. at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
  21. at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
  22. at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
  23. at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99)
  24. at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105)
  25. at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40)
  26. at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
  27. at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
  28. at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
  29. at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
  30. at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
  31. at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
  32. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  33. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  34. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  35. at java.base/java.lang.reflect.Method.invoke(Method.java:564)
  36. at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
  37. at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
  38. at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
  39. at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
  40. at com.sun.proxy.$Proxy5.processTestClass(Unknown Source)
  41. at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
  42. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
  43. at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
  44. at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
  45. at java.base/java.lang.reflect.Method.invoke(Method.java:564)
  46. at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
  47. at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
  48. at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
  49. at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
  50. at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
  51. at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
  52. at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
  53. at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
  54. at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
  55. at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
  56. at java.base/java.lang.Thread.run(Thread.java:832)
  57. app.transcriber.example.generated.SourceToTargetMapperTest > TestApply FAILED
  58. java.lang.NullPointerException at SourceToTargetMapperTest.java:87
  59. 1 test completed, 1 failed

答案1

得分: 1

你有一个简单的映射器,为什么要使用模拟进行测试呢?只需使用一些输入调用它并检查输出即可。

如果你坚持的话:异常是因为你试图监视通过调用targetModelObjectFactory.create(Target.class)来创建的对象,而targetModelObjectFactory已经是一个模拟对象 - 你不能这样做,对模拟对象调用的create会返回null。要么创建一个真实的Target,要么创建一个真实的Factory

英文:

You have a simple mapper, why on earth would you use mocks for testing that? Just call it with some input and check the output.

And if you insist: the exception is because you are trying to spy an object created by calling targetModelObjectFactory.create(Target.class) and targetModelObjectFactory is a mock already - you cannot do that, the create called on a mock returns null. Either create a real Target or a real Factory.

答案2

得分: 0

  1. 如果你遇到空指针异常,使用Mockito.RETURNS_DEEP_STUBS参数,我们告诉Mockito创建一种深层模拟。这使得可以对整个方法的结果进行模拟。
  2. <Class_Name> ref = Mockito.mock(Class_Name.class, Mockito.RETURNS_DEEP_STUBS);
英文:

if you get a nullpointer exception use Mockito.RETURNS_DEEP_STUBS argument, we tell Mockito to make a kind of deep mock. This makes it possible to mock the result of a complete method.

  1. &lt;Class_Name&gt; ref = Mockito.mock(Class_Name.class, Mockito.RETURNS_DEEP_STUBS);

huangapple
  • 本文由 发表于 2020年10月24日 06:16:24
  • 转载请务必保留本文链接:https://go.coder-hub.com/64507923.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定