Sharat Chandra
Sharat Chandra

Reputation: 4544

How to call mock method instead of real method in mockito/Junit

I want to call ClassA.mockMethod() whenever objOfClassB.realMethod() method is invoked.

public class ClassA{
     public static int mockMethod(String url, MySql sql){
        int res=0
        // do work
        return ;
    }

}

Definition of executeUpdate1()
class Veps{
    protected synchronized int realMethod(String url, MySql sql){
    ----
    -----
    }
}

public class VepsTest {
        public void setUp() throws Exception {

            veps = mock(Veps.class);

            when(objOfClassA.realMethod(any(String.class), any())).thenReturn(objOfClassB.mockMethod(any(String.class),any()));
         }
}


org.mockito.exceptions.misusing.InvalidUseOfMatchersException: 
Invalid use of argument matchers!
2 matchers expected, 4 recorded.
This exception may occur if matchers are combined with raw values:
    //incorrect:
    someMethod(anyObject(), "raw String");
When using matchers, all arguments have to be provided by matchers.
For example:
    //correct:
    someMethod(anyObject(), eq("String by matcher"));

Upvotes: 0

Views: 449

Answers (1)

holi-java
holi-java

Reputation: 30686

the mockito reports the errors clearly:

Invalid use of argument matchers! 2 matchers expected, 4 recorded.

you shouldn't using Matchers in any then* clause. your problem can be fixed as:

when(veps.executeQuery1(any(String.class), any(MySql.class)))
     .thenReturn(DBConnection.mockExecuteQuery("??","??"));

when(veps.executeUpdate1(any(String.class), any()))
     .thenReturn(DBConnection.mockExecuteUpdate("??","??"));

but another problem appears: why did you need query the result from the database? you can simply take a constant value to fake the result:

when(veps.executeQuery1(any(String.class), any(MySql.class)))
     .thenReturn(1);
//               ^--- replace the constant 1 with yours

when(veps.executeUpdate1(any(String.class), any()))
     .thenReturn(1);
//               ^--- replace the constant 1 with yours

you need to see mockito documentation as further before using it in your test.

Upvotes: 1

Related Questions