Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to mock a single method in java

Tags:

java

mocking

Is it possible to Mock a single method of a Java class?

For example:

class A {     long method1();     String method2();     int method3(); }   // in some other class class B {     void someMethod(A a) {        // how would I mock A.method1(...) such that a.method1() returns a value of my        // choosing;        // whilst leaving a.method2() and a.method3() untouched.     } } 
like image 943
auser Avatar asked Jun 05 '12 10:06

auser


People also ask

How do you mock a method in the same class?

We can mock runInGround(String location) method inside the PersonTest class as shown below. Instead of using mock(class) here we need to use Mockito. spy() to mock the same class we are testing. Then we can mock the method we want as follows.

How do you use mock method?

mock() method with Class: It is used to create mock objects of a concrete class or an interface. It takes a class or an interface name as a parameter. mock() method with Answer: It is used to create mock objects of a class or interface with a specific procedure.

How do you mock a private method?

For Mockito, there is no direct support to mock private and static methods. In order to test private methods, you will need to refactor the code to change the access to protected (or package) and you will have to avoid static/final methods.


2 Answers

Use Mockito's spy mechanism:

A a = new A(); A aSpy = Mockito.spy(a); Mockito.when(aSpy.method1()).thenReturn(5l); 

The use of a spy calls the default behavior of the wrapped object for any method that is not stubbed.

Mockito.spy()/@Spy

like image 120
John B Avatar answered Oct 03 '22 09:10

John B


Use the spy() method from Mockito, and mock your method like this:

import static org.mockito.Mockito.*;  ...  A a = spy(new A()); when(a.method1()).thenReturn(10L); 
like image 27
npe Avatar answered Oct 03 '22 11:10

npe