0

Trying to mock SQLQueryFactory of Querydsl for DAO unit testing. Using Mockito's deep stub for the very first time. Below is the minimal code which fails

@Test void tryMockQueryDsl() { SQLQueryFactory sql = Mockito.mock(SQLQueryFactory.class, Mockito.RETURNS_DEEP_STUBS); Mockito.when(sql.select(ArgumentMatchers.<Expression<?>>any()) .from(ArgumentMatchers.<Expression<?>>any()) .fetchFirst() ).thenReturn(null); } 

with the following exception:

java.lang.ClassCastException: class com.querydsl.sql.ProjectableSQLQuery$MockitoMock$1584151766 cannot be cast to class com.querydsl.sql.SQLQuery (com.querydsl.sql.ProjectableSQLQuery$MockitoMock$1584151766 and com.querydsl.sql.SQLQuery are in unnamed module of loader 'app')

What can be the problem?

0

1 Answer 1

0

Mocks can not be cast. Instead of RETURN_DEEP_STUBS mock each method on its own and return a mocked instance of the expected class.

If you do not want to suppress the warnings you will get for not defining the generic types, you can use the @Mock annotation instead to create the mocks, like described here.

This example doesn't make much sense for a testcase (as it tests nothing), but its a showcase on how to avoid the exception.

@RunWith(MockitoJUnitRunner.class) public class Test { @Test public void tryMockQueryDsl() { ProjectableSQLQuery projectableQuery = Mockito.mock(ProjectableSQLQuery.class); // not really needed as this is the default behaviour Mockito.when(projectableQuery.fetchFirst()).thenReturn(null); SQLQuery query = Mockito.mock(SQLQuery.class); Mockito.when(query.from(ArgumentMatchers.<Expression<?>>any())).thenReturn(projectableQuery); SQLQueryFactory sql = Mockito.mock(SQLQueryFactory.class); Mockito.when(sql.select(ArgumentMatchers.<Expression<?>>any())).thenReturn(query); Expression expr = Mockito.mock(Expression.class); sql.select(expr).from(expr).fetchFirst(); } } 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.