Version 3

    There are number of issues that people are facing while working with jBPM and to get help the most useful elements are:

    • process definition (BPMN2 file)
    • test case that illustrates mentioned issue

     

    As process definition is concerned that is rather straight forward (since we already working with it when encountering the problem),

    but with test case it can be bit more complex to give directly to others the driver we use for our case.

     

    So, after struggling for some time with exactly the same issue, I decided to start with small but yet powerful support for test cases for jBPM.

    There is already a test case class that we could extend and that already brings some useful elements but that is not all we need...

     

    I tried to build up a small library that is dedicated to test cases based on JUnit and that aligns with latest releases of JUnit, meaning it is

    based on annotations. So to move directly what I am referring to, lets take a look at very simple test case:

     

     

    @RunWith(JbpmJUnitRunner.class)
    @KnowledgeBase(source={"script.bpmn2"})
    @KnowledgeSession()
    public class JbpmJUnitTestCase {
    
        protected org.drools.KnowledgeBase knowledgeBase;
        protected StatefulKnowledgeSession session;
    
        @Test
        public void testScriptTask() {
            ProcessInstance instance = session.startProcess("ScriptTask");
            assertProcessInstanceComplete(instance);
        }
    }
    

     

    What you can see here is the most basic test case that allows to execute and assert process instance completion. I think the code is self explanatory so

    I jump directly to the annotations that were introduced with this library:

    @RunWith - this one is standard JUnit annotation that instructs what runner should be used to execute tests

    @KnowledgeBase - annotation that defines what artifacts should be loaded into knowledge base

        Annotation attributes:

    •     source - list of resources to be loaded (currently only BPMN2 and DRL resources are supported)
    •     sharedKey - name of the key that will be used to cache knowledge based between test cases, so if you have set of resources that are used across various

                    test cases and you want to avoid building knowledge base for each of the test cases sharedKey attribute should be set to load knowledge base only one time

     

    @KnowledgeSession - annotation that defines how stateful sessions should be created and maintained

        Annotation attributes:

    •     disposePerTest - defines if session should be disposed after each test within test case, default set to true
    •     logger - defines what working memory logger should be configured for the session, available options NONE (default), CONSOLE, JPA
    •     handlers - set of work item handlers that will be registered for each session (WorkItemHandler annotation)
    •     persistence - defines persistence for the session (Persistence annotation)

     

            @Persistence annotation attributes:

    •     persistenceUnit - name of the persistence unit that should be used while configuring JPA entity manager factory
    •     reloadSession - defines if session should be reloaded (with the same id) between test invocation within test case, default false

     

            @WorkItemHandler annotation attributes:

    •      taskName - name of the task the handler is registered for
    •      handles - class of the handler

     

    @HumanTaskSupport - annotation that instructs runner that test case requires Human Task interactions so it will initialize Task Server accessible via MINA transport

                it will be started on test case scope, meaning that all tests will have access to the same instance of the server within test case.

                Annotation attributes:

    •             users - list of user ids that should be added to the task server on startup
    •             groups - list of groups that should be added to the task server on startup
    •             persistanceUnit - name of the persistence unit that should be used while building entity manager factory
    •             host - interface on which task server should be started, defaults to localhost
    •             port - port on which task server should be started, defaults to 9123

     

    @LifeCycle - annotation that lets developer to configure what operation should be executed for particular human task.

         Annotation attributes:

    •      phases - list of human task life cycle phases (claim, start, complete, fail, skip, etc) defined as enumeration LifeCyclePhase

    This annotation is intended to simplify work with human tasks while writing unit tests - very experimental!!!

     

    In addition to annotation there are two property files required when configuring session persistence or human task server:

    • datasource.properties - defines parameters of connection pool
    • jndi.properties - defines JNDI provider for bitronix

     

    NOTE: Connection pool will be created for entire test phase once datasource.properties file was discovered.

     

    Obviously following files are required as well, since they are required by jbpm and task server artifacts:

    • META-INF/persistence.xml that defines both (jbpm and human task persistence units)
    • META-INF/JBPMorm.xml
    • META-INF/Taskorm.xml

     

    Main concept is around injecting dependencies into your test case class. As dependencies I mean following items:

    • Knowledge base
    • Stateful session
    • Task client

     

    Methods from JUnit life cycle are still available, such as these annotated with @Before, @After, @BeforeClass, @AfterClass. Instance methods (@Before @After) will

    have access to session and knowledge base, for instance if some facts should be inserted before running the test.

     

    There is one more item that is worth to mention, an assert class dedicated to jbpm - JbpmAssert, which defines (at the moment):

    • assertProcessInstanceComplete
    • assertProcessInstanceActive
    • assertProcessInstanceAborted
    • assertProcessInstancePending
    • assertProcessInstanceSuspended

     

    and most likely more to come...

     

    And now, its time to show some examples of it

     

    Simple test case with session persistence:

     

    @RunWith(JbpmJUnitRunner.class)
    @KnowledgeBase(source={"script.bpmn2"})
    @KnowledgeSession(persistence=@Persistence(persistenceUnit="org.jbpm.persistence.jpa"))
    public class JbpmJUnitTestCase {
    
        protected org.drools.KnowledgeBase knowledgeBase;
        protected StatefulKnowledgeSession session;
    
        @Test
        public void testScriptTask() {
            ProcessInstance instance = session.startProcess("ScriptTask");
            assertProcessInstanceComplete(instance);
        }
    }
    

     

    If session reload is desired between tests test case should be defined as follows:

     

     

    @RunWith(JbpmJUnitRunner.class)
    @KnowledgeBase(source={"script.bpmn2"})
    @KnowledgeSession(persistence=@Persistence(persistenceUnit="org.jbpm.persistence.jpa", reloadSession=true))
    public class JbpmJUnitTestCase {
    
        protected org.drools.KnowledgeBase knowledgeBase;
        protected StatefulKnowledgeSession session;
    
        @Test
        public void testScriptTask() {
            ProcessInstance instance = session.startProcess("ScriptTask");
            assertProcessInstanceComplete(instance);
        }
        @Test
        public void testScriptTask2() {
            ProcessInstance instance = session.startProcess("ScriptTask");
            assertProcessInstanceComplete(instance);
        }
    }
    

     

    Both tests will use same session.

     

    Last but not least, human interaction test case:

     

     

    @RunWith(JbpmJUnitRunner.class)
    @KnowledgeBase(source={"script.bpmn2","usertask.bpmn2"}, sharedKey="common")
    @KnowledgeSession(handlers={@WorkItemHandler(taskName="Human Task", handler=WSHumanTaskHandler.class)}, logger=Logger.CONSOLE)
    @HumanTaskSupport(persistenceUnit="org.jbpm.task", users={"john", "Administrator"})
    public class JbpmJUnitRunnerTest {
    
        protected org.drools.KnowledgeBase knowledgeBase;
        protected StatefulKnowledgeSession session;
        protected TaskClient taskClient;
    
        @Test
        public void testHumanTask() throws Exception {
            ProcessInstance instance = session.startProcess("UserTask");
            Thread.sleep(1000);
            BlockingTaskSummaryResponseHandler taskSummaryHandler = new BlockingTaskSummaryResponseHandler();
            taskClient.getTasksAssignedAsPotentialOwner("john", "en-UK", taskSummaryHandler);
    
            assertEquals(1, taskSummaryHandler.getResults().size());
            TaskSummary task1 = taskSummaryHandler.getResults().get(0);
    
            BlockingTaskOperationResponseHandler taskOperationHandler = new BlockingTaskOperationResponseHandler();
            taskClient.claim(task1.getId(), "john", taskOperationHandler);
    
            taskOperationHandler = new BlockingTaskOperationResponseHandler();
            taskClient.start(task1.getId(), "john", taskOperationHandler);
            taskOperationHandler.waitTillDone(1000);
    
            taskOperationHandler = new BlockingTaskOperationResponseHandler();
            taskClient.complete(task1.getId(), "john", null, taskOperationHandler);
            taskOperationHandler.waitTillDone(1000);
    
            Thread.sleep(1000);
    
            assertProcessInstanceComplete(instance);
        }
    }
    

     

    In the example we can notice several configurations elements:

    • knowledge base is configured to be shared between test cases under 'common' shared key
    • knowledge session will have registered handler for 'Human Task' work items
    • knowledge session will have a console logger configured
    • human task server will be configured with 'org.jbpm.task' persistence unit and will add two users once it's started (john, Administrator)

     

    As mentioned on the comments, working with human tasks is still quite complex so an alternative approach is introduced:

     

    @RunWith(JbpmJUnitRunner.class)
    @KnowledgeBase(source={"script.bpmn2","service.bpmn2","usertask.bpmn2"}, sharedKey="common")
    @KnowledgeSession(handlers={@WorkItemHandler(taskName="Service Task", handler=ServiceTaskHandler.class),
                        @WorkItemHandler(taskName="Human Task", handler=WSHumanTaskHandler.class)}, logger=Logger.CONSOLE)
    @HumanTaskSupport(persistenceUnit="org.jbpm.task", users={"john", "Administrator"})
    public class JbpmJUnitRunnerTest {
    
              protected org.drools.KnowledgeBase knowledgeBase;
              protected StatefulKnowledgeSession session;
              protected TestTaskClient taskClient;
    
            @Test
              @LifeCycle(phases={LifeCyclePhase.CLAIM, LifeCyclePhase.START, LifeCyclePhase.COMPLETE})
              public void testHumanTask() throws Exception {
                        ProcessInstance instance = session.startProcess("UserTask");
    
                        taskClient.performLifeCycle("john", "en-UK", null);
    
                        assertProcessInstanceComplete(instance);
              }
    }
    

     

    So, here you can see a quite substantial change in code lines to achieve exactly the same result as previous example. So at the method level you can define what life cycle operation of human task you would like to invoke, using @LifeCycle annotation. That of course is interesting if you would like to invoke exactly the same life cycle phases for all your human tasks within test case, for instance testing positive path for the entire process.

    But if you would like to have it on task instance level you can specify the phases on execution of performLifeCycel method of testTaskClient.

     

    An extension of regular TaskClient was introduced (TestTaskClient) that was equipped with two methods:

     

    performLifeCycle(String user, String targetUser, String locale, HashMap input)
    performLifeCycle(String user, String targetUser, String locale, HashMap input, LifeCyclePhase[] phases)
    

     

    obviously it does not cover all possible use cases but as it was said it is experimental and will be enhanced hopefully soon (if you find it useful).

    So far following life cycle phases are available:

    • claim
    • start
    • stop
    • complete
    • fail
    • skip
    • remove
    • release
    • suspend
    • resume
    • delegate
    • forward

    Note that there is not consistency check of defined phases in test case, meaning that if you use exclusive phases you will get errors, for instance complete and fail. If you have operations that cause task to be reassigned, for instance delegate than you need to invoke performLifeCycle method twice.

     

            @Test
              @LifeCycle(phases={LifeCyclePhase.START, LifeCyclePhase.DELEGATE})
              public void testHumanTask() throws Exception {
                        ProcessInstance instance = session.startProcess("UserTask");
    
                        taskClient.performLifeCycle("john", "mike", "en-UK", null);
                        taskClient.performLifeCycle("mike", null, "en-UK", null, new LifeCyclePhase[]{LifeCyclePhase.START, 
                                                                                                                                                  LifeCyclePhase.COMPLETE});
      
                        assertProcessInstanceComplete(instance);
              }
    
    

     

    Global configuration

    Another thing was added to the mentioned test support - possibility to configure your tests globally.

    So what does it mean? Generally it allows to configure same components as annotations but in the scope of the project or maven module by defining it as simple properties file. Main benefits of this approach are as follows:

    • single configuration for all test cases (no need to put annotations in your test case class
    • possibility to share knowledge base for all your tests (will be loaded only once)
    • can run the same test suit with different properties set to verify various configuration without a need to modify test cases
    • annotations can be used to override global configuration

     

    Here an example of jbpm-test.properties file:

     

    #knowledge base configuration
    #mandatory properties
    knowledge.base.source=script.bpmn2;service.bpmn2;usertask.bpmn2
    #optional properties
    knowledge.base.shared.key=common
    
    #knowledge session configuration
    #all of them are optional with defaults
    session.dispose.per.test=true
    session.logger=FILE
    #session.persistence.unit=
    #session.persistence.reload=
    session.workitem.handlers=Service Task:org.jbpm.bpmn2.handler.ServiceTaskHandler;Human Task:org.jbpm.process.workitem.wsht.WSHumanTaskHandler;
    
    #human task service configuration
    #mandatory properties
    human.task.persistence.unit=org.jbpm.task
    
    #optional parameters that are default to localhost and 9123
    human.task.users=john;Administrator
    #human.task.groups=
    #human.task.host=
    #human.task.port=
    
    

     

    Currently, junit runner expects to find it on root of the classpath and with exactly the name of jbpm-test.properties. Will be enhanced with next update of code base to support extensions, for instance using -D parameters of jvm.

     

     

    Ok, so that is it! I hope you can provide some feedback about it and hopefully we can get a valuable discussion around it and what's even more important

    maybe we start using it on daily basis so everybody could benefit from it.

    Attached draft version of the library.

     

    Looking forward to your comments

     

    P.S.

    If you are interested in the complete module you can find it at: https://github.com/mswiderski/jbpm/tree/master/jbpm-test-support It is now merged with the jBPM code base as additional module