Introduction
In this tutorial we will see how to mock Activiti
TaskService
, TaskQuery
, NativeTaskQuery
in Junit class. Suppose you have Spring service class where you are doing some business flow for your application. So you are using Activiti
‘s TaskService
to create a list of activiti Tasks
using the method createNativeTaskQuery()
.
You may need to create also TaskQuery
from TaskService
using createTaskQuery()
method.
Therefore here, we will see how to mock Activiti TaskService
, TaskQuery
, NativeTaskQuery
in Junit class.
Prerequisites
Knowledge of Junit
Mock using Junit
Let’s move on to the implementation…
Service Class
Suppose you have below Spring service class, where you have autowired TaskService
. You also have below methods and inside these methods you are returning a list of Task
instances using NativeTaskQuery
and TaskQuery
as per your requirement of the application.
In the first method we are creating NativeTaskQuery
and returning a list of Task
instances.
In the second method we are creating TaskQuery
and here we are retrieving data from database by passing process definition key. We are not using any database specific SQL statement, so here we are using TaskQuery
.
@Service
public class SpringService {
@Autowired
private TaskService tskSrv;
public void method1() {
...
List<Task> result = tskSrv.createNativeTaskQuery().sql("sql query").list();
...
}
public void method2(String processDefinitionKey) {
...
List<Task> outStandingTasks = tskSrv.createTaskQuery().active().processDefinitionKey(processDefinitionKey).list();
...
}
}
Why NativeTaskQuery?
We are using database specific SQL statement to fetch the data from database, so we need to use NativeTaskQuery
.
Junit Class
Let’s create our Junit test class…
In the below Junit test class notice how we have mocked the activiti’s TaskService
, TaskQuery
, TaskNativeQuery
.
@RunWith(MockitoJUnitRunner.class)
public class SpringServiceTest {
@Mock
private TaskService tskSrv;
@Mock
private NativeTaskQuery nativeTaskQuery;
@Mock
private TaskQuery taskQuery;
@Test
public void testMethod1() {
...
Mockito.when(tskSrv.createNativeTaskQuery()).thenReturn(nativeTaskQuery);
Mockito.when(nativeTaskQuery.sql(Mockito.anyString())).thenReturn(nativeTaskQuery);
...
}
@Test
public void testMethod1() {
...
Mockito.when(tskSrv.createTaskQuery()).thenReturn(taskQuery);
Mockito.when(taskQuery.active()).thenReturn(taskQuery);
Mockito.when(taskQuery.processDefinitionKey(Mockito.anyString())).thenReturn(taskQuery);
Mockito.when(taskQuery.list()).thenReturn(new ArrayList<>());
...
}
}
That’s all. Hope you got an idea how to mock Activiti TaskService, TaskQuery, NativeTaskQuery in Junit.
Thanks for reading.