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

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

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:

public Target apply(Source source) throws MappingException {
    try {
        Target target = targetModelObjectFactory.create(Target.class);
        // ... (other method calls)
        return target;
    } catch (Exception e) {
        throw new MappingException(source, e);
    }
}

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

@Test
public void TestSettingMappedMailFromSourceToTargetEMail() {
    Source mockedSource = Mockito.mock(Source.class);
    Target mockedTarget = Mockito.mock(Target.class);

    sourceToTargetMapper.mapMailToEMail(mockedSource, mockedTarget);
    Mockito.verify(mockedTarget, Mockito.times(1)).setEMail(mockedSource.getMail());
}

And here is a part of my test:

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

The problem that I'm having is with this part

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

java.lang.NullPointerException
    at org.mockito.Mockito.spy(Mockito.java:2034)
    at app.transcriber.example.generated.SourceToTargetMapperTest.TestApply(SourceToTargetMapperTest.java:87)
    at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    // ... (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:

public Target apply(Source source) throws MappingException {
    try {
      Target target = targetModelObjectFactory.create(Target.class);
      mapNameToFirstName(source, target);
      mapMailToEMail(source, target);
      mapSourceSubEntityToTargetSubEntity(source, target);
      mapPrimitiveSourceColToPrimitiveTargetCol(source, target);
      mapSubEntitiesSourceColToSubEntitiesTargetCol(source, target);
      mapSourceSubEntityFieldToSubEntityFetchedField(source, target);
      produceProducedFieldValue(target);
      setConstantFieldConstantValue(target);
      return target;
    } catch (Exception e) {
      throw new MappingException(source, e);
    }
  }

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

@Test
    
    public void TestSettingMappedMailFromSourceToTargetEMail() {

        Source mockedSource = Mockito.mock(Source.class);
        Target mockedTarget = Mockito.mock(Target.class);

        sourceToTargetMapper.mapMailToEMail(mockedSource, mockedTarget);
        Mockito.verify(mockedTarget, Mockito.times(1)).setEMail(mockedSource.getMail());
    }

And here is a part of my test:

@Test
    public void TestApply() throws MappingException, MappingOperatorCreationException, TargetModelObjectCreationException {

        Source mockedSource = Mockito.mock(Source.class);
        TargetModelObjectFactory targetModelObjectFactory = Mockito.mock(TargetModelObjectFactory.class)
        Target mockedTarget = Mockito.spy(targetModelObjectFactory.create(Target.class));
        sourceToTargetMapper.mapNameToFirstName(mockedSource,mockedTarget);
        Mockito.verify(mockedSource,Mockito.times(1)).setMail(mockedSource.getMail());
}

The problem that I'm having is with this part

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

java.lang.NullPointerException
	at org.mockito.Mockito.spy(Mockito.java:2034)
	at app.transcriber.example.generated.SourceToTargetMapperTest.TestApply(SourceToTargetMapperTest.java:87)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:50)
	at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:12)
	at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:47)
	at org.junit.internal.runners.statements.InvokeMethod.evaluate(InvokeMethod.java:17)
	at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:26)
	at org.mockito.internal.runners.DefaultInternalRunner$1$1.evaluate(DefaultInternalRunner.java:54)
	at org.junit.runners.ParentRunner.runLeaf(ParentRunner.java:325)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:78)
	at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:57)
	at org.junit.runners.ParentRunner$3.run(ParentRunner.java:290)
	at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:71)
	at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:288)
	at org.junit.runners.ParentRunner.access$000(ParentRunner.java:58)
	at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:268)
	at org.junit.runners.ParentRunner.run(ParentRunner.java:363)
	at org.mockito.internal.runners.DefaultInternalRunner$1.run(DefaultInternalRunner.java:99)
	at org.mockito.internal.runners.DefaultInternalRunner.run(DefaultInternalRunner.java:105)
	at org.mockito.internal.runners.StrictRunner.run(StrictRunner.java:40)
	at org.mockito.junit.MockitoJUnitRunner.run(MockitoJUnitRunner.java:163)
	at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.runTestClass(JUnitTestClassExecutor.java:110)
	at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:58)
	at org.gradle.api.internal.tasks.testing.junit.JUnitTestClassExecutor.execute(JUnitTestClassExecutor.java:38)
	at org.gradle.api.internal.tasks.testing.junit.AbstractJUnitTestClassProcessor.processTestClass(AbstractJUnitTestClassProcessor.java:62)
	at org.gradle.api.internal.tasks.testing.SuiteTestClassProcessor.processTestClass(SuiteTestClassProcessor.java:51)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
	at org.gradle.internal.dispatch.ContextClassLoaderDispatch.dispatch(ContextClassLoaderDispatch.java:33)
	at org.gradle.internal.dispatch.ProxyDispatchAdapter$DispatchingInvocationHandler.invoke(ProxyDispatchAdapter.java:94)
	at com.sun.proxy.$Proxy5.processTestClass(Unknown Source)
	at org.gradle.api.internal.tasks.testing.worker.TestWorker.processTestClass(TestWorker.java:119)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at java.base/jdk.internal.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
	at java.base/jdk.internal.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
	at java.base/java.lang.reflect.Method.invoke(Method.java:564)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:36)
	at org.gradle.internal.dispatch.ReflectionDispatch.dispatch(ReflectionDispatch.java:24)
	at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:182)
	at org.gradle.internal.remote.internal.hub.MessageHubBackedObjectConnection$DispatchWrapper.dispatch(MessageHubBackedObjectConnection.java:164)
	at org.gradle.internal.remote.internal.hub.MessageHub$Handler.run(MessageHub.java:414)
	at org.gradle.internal.concurrent.ExecutorPolicy$CatchAndRecordFailures.onExecute(ExecutorPolicy.java:64)
	at org.gradle.internal.concurrent.ManagedExecutorImpl$1.run(ManagedExecutorImpl.java:48)
	at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1130)
	at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:630)
	at org.gradle.internal.concurrent.ThreadFactoryImpl$ManagedThreadRunnable.run(ThreadFactoryImpl.java:56)
	at java.base/java.lang.Thread.run(Thread.java:832)

app.transcriber.example.generated.SourceToTargetMapperTest > TestApply FAILED
    java.lang.NullPointerException at SourceToTargetMapperTest.java:87
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

如果你遇到空指针异常,使用Mockito.RETURNS_DEEP_STUBS参数,我们告诉Mockito创建一种深层模拟。这使得可以对整个方法的结果进行模拟。

<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.

&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:

确定