Category Archives: mockito

[Solved] org.mockito.exceptions.misusing.UnnecessaryStubbingException


UnnecessaryStubbingException is runtime and sub class of MockitoException. Mockito JUnit Runner triggers UnnecessaryStubbingException only when none of the test methods use the stubbings. This means that it is ok to put default stubbing in a ‘setup’ method or in test class constructor. That default stubbing needs to be used at least once by one of the test methods.

Constructors

  • UnnecessaryStubbingException(String message) : Will throw exception with message.

Example

//code test:
 String result = translator.translate("Saurabh");

//Mock:
// <- stubbing used during code execution
 when(translator.translate("Saurabh")).thenReturn("Gupta");
// <- stubbing never used
when(translator.translate("Gaurav")).thenReturn("Gupta");

Solutions

It is highly recommended to remove unused stubbings to keep the codebase clean. You can opt-out from detecting unused stubbing using MockitoJUnitRunner.Silent() or MockitoRule.silent() (when you are using Mockito JUnit rules.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/UnnecessaryStubbingException.html

Know More

To know more about Junit, Mockito and exception solutions follow below links:

[Solved] org.mockito.exceptions.misusing.PotentialStubbingProblem


PotentialStubbingProblem is a RuntimeException and subclass of MockitoException. Mockito framework throws this exception when “stubbing arguments mismatch“.

Strict stubbing is a new opt-in feature for JUnit Rule and JUnit Runner to detect potential stubbing problems org.mockito.exceptions.misusing.PotentialStubbingProblem exception is thrown when mocked method is stubbed with some argument in test but then invoked with different argument in code.

This exception can occurred by many reasons:

  1. Mistake or typo in the test code, the argument(s) used when declaring stubbing’s is unintentionally different.
  2. Mistake or typo in the code under test, the argument(s) used in the code under test is unintentionally different.
  3. Intentional use of stubbed method with different argument, either in the test (more stubbing) or in code under test.

Constructors

  • PotentialStubbingProblem(String message) : Will throw exception with message.

Example

 //test method:
 given(mock.getSomething(200)).willReturn(something);

 //code under test:
// stubbing argument mismatch
 Something something = mock.getSomething(100);

Solutions

public class TestExample {
     @Rule
     public MockitoRule rule = MockitoJUnit.rule().strictness(Strictness.STRICT_STUBS);

     @Test public void exampleTest() {
         //Change the strictness level only for this test method:
         mockito.strictness(Strictness.LENIENT);

         //remaining test code
         given(mock.getSomething(200)).willReturn(something);
         //Will work
         Something something = mock.getSomething(100);

     }
 }

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/PotentialStubbingProblem.html

Know More

To know more about Junit, Mockito and exception solutions follow below links:

[Solved] org.mockito.exceptions.misusing.RedundantListenerException


RedundantListenerException is RuntimeException and sub class of MockitoException. This occurred by Mockito framework when  instance of MockitoListener is being added to Mockito Framework and there is already a listener with this implementation type registered.

Note : It is ok to add multiple different implementations of the same listener interface type.

Constructors

  • RedundantListenerException(String message) : Will throw exception with message.

Example

MockitoFramework.addListener(MockitoListener);

Solutions

If you are trying to add the listener but a listener of the same type was already added (and not removed) this method will throw RedundantListenerException. This is a safeguard to ensure users actually remove the listeners via removeListener. We do not anticipate the use case where adding the same listener type multiple times is useful.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/RedundantListenerException.html

Know More

To know more about Junit, Mockito and exception solutions follow below links:

[Solved]org.mockito.exceptions.base.MockitoException


MockitoException  is RuntimeException raised by Mockito framework to emit an error either due to Mockito, or due to the User. Mockito throws exception in form of stacktrace with suggested solutions.

StackTrace for Application calls:

StackTraceElement[] Throwable.getStackTrace()

StackTrace with Mockito and API calls:

StackTraceElement[] getUnifilteredStackTrace()

Constructors

  • MockitoException(String message) : Will throw exception with message.
  • MockitoException(String message, Throwable T) : Will throw exception with message and stacktrace.

Mockito Exception Subclasses

MockitoException Hierarchy
MockitoException Hierarchy

Example

In below example , using OngoingStubbing on mock object of Map interface where setting stub object for get() method which accept any input String and return response as String as set in thenReturn() method.

import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.Map;

import org.junit.Assert;
import org.junit.Test;
import org.mockito.exceptions.base.MockitoException;
import org.mockito.stubbing.OngoingStubbing;

public class MockitoApplicationTester {

@Test
public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception {
// Mock of Map interface
Map<String, String> map = mock(Map.class);

OngoingStubbing<String> mapOngoingStubbing = when(map.get(anyString()));
try {
mapOngoingStubbing.thenReturn("1st stubbing");
//This method will throw exception
mapOngoingStubbing.thenReturn("2nd stubbing");
Assert.assertEquals(map.get("Test"), "1st stubbing");
} catch (MockitoException e) {
StackTraceElement[] stacks = e.getStackTrace();
for (StackTraceElement stack : stacks) {
System.out.println(stack.getMethodName());
}

StackTraceElement[] ustacks = e.getUnfilteredStackTrace();
for (StackTraceElement stack : ustacks) {
System.out.println(stack.getMethodName());
}
throw e;

}
}

Output

org.mockito.exceptions.base.MockitoException:
Incorrect use of API detected here:
-> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_IndexOutOfBoundsException(MockitoApplicationTester.java:48)

You probably stored a reference to OngoingStubbing returned by when() and called stubbing methods like thenReturn() on this reference more than once.
Examples of correct usage:
when(mock.isOk()).thenReturn(true).thenReturn(false).thenThrow(exception);
when(mock.isOk()).thenReturn(true, false).thenThrow(exception);

at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_IndexOutOfBoundsException(MockitoApplicationTester.java:48)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)<span 				data-mce-type="bookmark" 				id="mce_SELREST_start" 				data-mce-style="overflow:hidden;line-height:0" 				style="overflow:hidden;line-height:0" 			></span>

Solutions

Above example is throwing MockitoException with message as “Incorrect use of API detected here”  because of thenReturn() method set two times value for single mock stub object. For solving above issue comment one of thenRetun() statement from try block.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/base/MockitoException.html#getUnfilteredStackTrace()

Know More

To know more about Junit, Mockito and exception solutions follow below links:

[Solved] org.mockito.exceptions.misusing.WrongTypeOfReturnValue


WrongTypeOfReturnValue is RuntimeException and Subclass of MockitoException.  It throws when :

  1.  It might occurred because of wrongly written multi-threaded tests.
  2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies with doReturn|Throw() family of methods. 

Constructors

  • WrongTypeOfReturnValue(String message) : Will throw exception with message.

Example

Below case to show you on what case Mockito will throw WrongTypeOfReturnValue .

import static org.mockito.Mockito.*;
import static org.junit.Assert.*;

import org.junit.Test;

public class NestedWhen {
public class Bar {
}

public class Foo {
Bar getBar() {
return new Bar();
}
}

public class Product {
Bar bar;

Product(Foo f) {
bar = f.getBar();
}
}

public class ProductService {
Foo foo;

ProductService(Foo f) {
foo = f;
}

Product produce() {
return new Product(foo);
}
}

@Test
public void nestedWhenTest() {
Foo mfoo = mock(Foo.class);
Product mpoo = mock(Product.class);
ProductService productService = spy(new ProductService(mfoo));
// throw WrongTypeOfReturnValue exception here!!!
when(productService.produce()).thenReturn(mpoo);
}
}

Output

org.mockito.exceptions.misusing.WrongTypeOfReturnValue:
NestedWhen$Product$$EnhancerByMockitoWithCGLIB$$4418933b cannot be returned by getBar()
getBar() should return Bar
***
If you're unsure why you're getting above error read on.
Due to the nature of the syntax above problem might occur because:
1. This exception *might* occur in wrongly written multi-threaded tests.
Please refer to Mockito FAQ on limitations of concurrency testing.
2. A spy is stubbed using when(spy.foo()).then() syntax. It is safer to stub spies -
- with doReturn|Throw() family of methods. More in javadocs for Mockito.spy() method.

at com.facingissuesonit.mockito.MockitoTestExamples.NestedWhen.nestedWhenTest(NestedWhen.java:44)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)

Solutions

Here above code is throwing this exception because spy execute the real code by nature, so when calling “productService.produce()” the expression is actually executed and return a real Product. The constructor of Product takes the constructor arg “foo” which is a mock and it executes “f.getBar()”. This invocation is recorded by mockito because this “foo” instance is a mock.

Then when you want to return “mpoo”, mockito raises the exception WrongTypeOfReturnValue saying that the recorded invocation “foo.getBar()” cannot return a Product.

If you want to mock a partial mock, which you should avoid if possible. You need to use the following style for spies, this way Mockito can tell the spy instance to only record the invocation.

doReturn(mpoo).when(productService).produce();

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/WrongTypeOfReturnValue.html

Know More

To know more about Junit, Mockito and exception solutions follow below links:

 

[Solved] org.mockito.exceptions.misusing.InvalidUseOfMatchersException


InvalidUseOfMatchersException is RuntimeException and subclass of MockitoException. It throws when trying to push behavior on object which is not mock.

Constructors

  • InvalidUseOfMatchersException() : Will throw exception.
  • InvalidUseOfMatchersException(String message) : Will throw exception with message.

Example

Here in below example mock Map interface and creating stub for get method to return fixed String for any type of String elements.


import static org.mockito.Matchers.anyString;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

import java.util.HashMap;
import java.util.Map;

import org.junit.Assert;
import org.junit.Test;

public class MockitoApplicationTester {

@Test
public void second_stubbing_throws_InCorrectUseOfAPI() throws Exception {
// Mock of Map interface
Map<String, String> mapMock = mock(Map.class);
Map<String, String> mapReal = new HashMap<String, String>();

//Issue is here because performing argument matcher without mock object
when(mapReal.get(anyString())).thenReturn("1st stubbing");

//Correct statement
when(mapMock.get(anyString())).thenReturn("1st stubbing");

Assert.assertEquals(mapMock.get("Test"), "1st stubbing");

}

}

Output


org.mockito.exceptions.misusing.InvalidUseOfMatchersException:
Misplaced argument matcher detected here:

-> at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22)

You cannot use argument matchers outside of verification or stubbing.
Examples of correct usage of argument matchers:
when(mock.get(anyInt())).thenReturn(null);
doThrow(new RuntimeException()).when(mock).someVoidMethod(anyObject());
verify(mock).someMethod(contains("foo"))

Also, this error might show up because you use argument matchers with methods that cannot be mocked.
Following methods *cannot* be stubbed/verified: final/private/equals()/hashCode().
Mocking methods declared on non-public parent classes is not supported.

at com.facingissuesonit.mockito.MockitoTestExamples.MockitoApplicationTester.second_stubbing_throws_InCorrectUseOfAPI(MockitoApplicationTester.java:22)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)

Solutions

Here in above code is throwing this exception because using real object to create stub that’s what throwing “InvalidUseOfArgumentMatchersException“. To fix above this comment out wrong statement and execute again.

This exception can occurred by others ways also:

  1. This error might show up because you use argument matchers with methods that cannot be mocked.
  2. Stubbed and verified method can be used on final/private/equals()/hashCode() methods.
  3. Mocking methods declared on non-public parent classes is not supported.

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/InvalidUseOfMatchersException.html

Know More

To know more about Junit, Mockito and exception solutions follow below links:

[Solved] org.mockito.exceptions.misusing.MissingMethodInvocationException


MissingMethodInvocationException is RuntimeException and subclass of MockitoException. It generally throws when:

  1. It might occurs when() requires an argument which has to be ‘a method call on a mock. For example:                when(mock.getArticles()).thenReturn(articles);
  2. You try to stubbed/verified either of: final/private/equals()/hashCode() methods.
  3. Mocking methods declared on non-public parent classes is not supported.
  4. Inside when() you don’t call method on real object always call from mock or spy.

Constructors

  • MissingMethodInvocationException(String message) : Will throw exception with message.

Example

To complete example follow link Mockito + JUnit Tutorial

import static org.mockito.Mockito.spy;

import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;

import static org.mockito.Mockito.*;
//@RunWith attaches a runner with the test class to initialize the test data
@RunWith(org.mockito.runners.MockitoJUnitRunner.class)
public class MathApplicationTestrSpy {
private CalculatorService calcService;

@Before
public void setUp(){
Calculator calculator = new Calculator();
calcService = spy(calculator);
//Issue is here because using actual object
when(calculator.add(20.0,10.0)).thenReturn(30.0);
}

@Test
public void testAdd(){
Assert.assertEquals(calcService.add(20.0, 10.0),30.0,0);
}

}

Output

org.mockito.exceptions.misusing.MissingMethodInvocationException:
when() requires an argument which has to be 'a method call on a mock'.
For example:
when(mock.getArticles()).thenReturn(articles);

Also, this error might show up because:
1. you stub either of: final/private/equals()/hashCode() methods.
Those methods *cannot* be stubbed/verified.
Mocking methods declared on non-public parent classes is not supported.
2. inside when() you don't call method on mock but on some other object.

at com.facingissuesonit.mockito.MockitoTestExamples.MathApplicationTestrSpy.setUp(MathApplicationTestrSpy.java:29)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:45)
at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:42)

Solutions

Here in above example trying stub on real object instead of mock and spy object. To solve this issue update code as below. For complete example please refer Mockito + JUnit TutorialMockito + JUnit Tutorial.


@Before
public void setUp(){
Calculator calculator = new Calculator();
calcService = spy(calculator);
//Issue is here because using actual object
//when(calcService.add(20.0,10.0)).thenReturn(30.0);

//Used Spy object
when(calculator.add(20.0,10.0)).thenReturn(30.0);
}

References

https://static.javadoc.io/org.mockito/mockito-core/2.6.5/org/mockito/exceptions/misusing/MissingMethodInvocationException.html

Know More

To know more about Junit, Mockito and exception solutions follow below links: