Java – mockito: wanted but not referenced

I have the following test methods:

MyClass myClass= Mockito.mock(MyClass.class);
Mockito.when(myClass.methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class))).thenReturn(Collections.<X,Y> emptyMap());

assertNull(myClass.methodToTest(myObject));
Mockito.verify(myClass).methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class));

Methodusedinmethodbeingtested is a method that I want to emulate and return null mappings But I received the news of failure

.

MyClass
{
   public XYZ methodTotest()
   {
    ....
    ....
    Map<X,Y> mp = methodUsedInMethodBeingTested(myTypeParam);
    .....
   }

   public Map<X,Y> methodUsedInMethodBeingTested(MyTypeParam myTypeParam)
   {
    .....
   }
}

Solution

You misunderstood what simulation is When you're doing it

MyClass myClass = Mockito.mock(MyClass.class);
// ...
assertNull(myClass.methodToTest(myObject));

You don't actually call methodtotest on a real object You call methodtotest on mock. By default, you do nothing and return null unless it is stubbed Quoted from mockito docs:

This explains your subsequent error: the method is not actually called on the simulation

It seems that what you want is spy, not:

But please note the warning: because it is the real method being called, you should not use mockito But I prefer mockito doReturn(…). Otherwise, the method will be called once as true If you consider expressions:

Mockito.when(myClass.methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class))).thenReturn(Collections.<X,Y> emptyMap());
             ^-----------------------------------^
                 this will be invoked by Java

The parameters of the method must be evaluated, but this means that the method methodusedinmethodbeingtested. Will be called Since we have a spy, this is the real method to be called So instead, use:

MyClass spy = Mockito.spy(new MyClass());
Mockito.doReturn(Collections.<X,Y> emptyMap()).when(spy).methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class));
assertNull(spy.methodToTest(myObject));
Mockito.verify(spy).methodUsedInMethodBeingTested(Matchers.any(MyTypeParam.class));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>