0

I am trying to use Mockito to mock a function call.

I have a method runQueryForDataWindow in a class called QueryBuilder. The method runQueryForDataWindow takes two arguments - 1) a string 2) an instance of class FetchWindow

runQueryForDataWindow(String str, FetchWindow fetchWindow)

Here is how my test case for mocking looks like

final QueryBuilder queryBuilder = mock(QueryBuilder.class);

Mockito.when(queryBuilder.runQueryForDataWindow(anyString(), 
            any(FetchWindow.class))).thenReturn(queryResult);

I want to return queryResult irrespective of the function arguments.

When I ran this, the test fails with org.mockito.exceptions.misusing.InvalidUseOfMatchersException

I guess there is something wrong with the way I am trying to pass in the instance of FetchWindow. Appreciate any leads here.

  • 1
    Show us the relevant code, and the complete stack trace of the exception. Tell us which line of code the exception refers to. – JB Nizet Dec 31 '14 at 11:38
  • 1
    The lines you posted look fine; the odd thing about Mockito matchers is that they can throw exceptions due to invalid use _above_ or _before_ the line that throws the exception. Post the preceding matcher usage and check that you're not trying to mock `final` methods, and consider some of the debugging steps [here](http://stackoverflow.com/q/22822512/1426891) including calling `Mockito.validateMockitoUsage` before the `when` you posted above. – Jeff Bowman Dec 31 '14 at 19:18
  • Thanks Jeff, JB. `runQueryForDataWindow` was actually a final method. I removed the final qualifier and retested. The InvalidUseOfMatchersException exception is gone but the method isn't getting mocked. I see the below stack trace now – Pankaj Agrawal Jan 05 '15 at 11:13
  • SEVERE: null java.sql.SQLException: The url cannot be null at java.sql.DriverManager.getConnection(DriverManager.java:556) at java.sql.DriverManager.getConnection(DriverManager.java:215) at test.repo.impl.JDBCClient.getConnection(JDBCClient.java:251) at test.repo.impl.JDBCClient.runQueryForDataWindow (QueryBuilder.java:184) at test.repo.impl.CollectorRepoImpl.createFetchWindows(CollectorRepoImpl.java:111) at test.repo.impl.CollectorRepoImpl.getDataSynchronously(CollectorRepoImpl.java:72) – Pankaj Agrawal Jan 05 '15 at 11:13
  • As the stack trace shows, getConnection is called from runQueryForDataWindow. However, had runQueryForDataWindow been successfully mocked, it should have returned queryResult. – Pankaj Agrawal Jan 05 '15 at 11:19
  • My test case is as follows: `QueryBuilder queryBuilder = mock(QueryBuilder.class); Mockito.validateMockitoUsage(); Mockito.when(queryBuilder.runQueryForDataWindow(anyString(), any(FetchWindow.class))).thenReturn(queryResult); new CollectorRepoImpl().getDataSynchronously (wlist);` – Pankaj Agrawal Jan 05 '15 at 11:19

0 Answers0