Introduction

I have been researching testing K2 workflows for a client over the last couple of days, and I came across this white paper in my library, so I thought I would share it with you all.

Development teams have been using automated tools such as Visual Studio Test System (VSTS) as part of their software development lifecycle to automate unit testing. This covers how to use VSTS to automate the unit testing of K2 processes. The same principles can be applied with other unit testing frameworks such as NUnit.

K2 processes are exposed directly through a client API as well as through a service layer, which includes WCF, REST and legacy SOAP services. This uses the client API, SourceCode.Workflow.Client, in VSTS unit tests to start and action K2 processes and check that they behave as expected.

We’ll set up a Visual Studio solution to test K2 processes. It includes a Framework class library with some classes that reduce the amount of code in each unit test and give the tests a common structure. Then there’s a set of best practices for unit testing K2 processes, followed by how-tos for different types of test.

Sample K2 workflow

This is the sample K2 process we will unit test. It contains a standard approval, a rework step that sends a task back to the originator, a placeholder step with a line rule, and a couple of placeholders for the approve and deny branches.

Set up the VSTS solution

This assumes you are familiar with Visual Studio, so the instructions are high level. It’s perfectly fine to add the test project to an existing solution if you prefer.

Create the Visual Studio solution

Create an empty solution, found in the Other Project Types category, or use an existing solution if you want to add the process tests to a suite of other unit tests.

Create the test framework project

Create a standard class library project in your solution. This library will house common entities and a ProcessHelper class with much of the common code used in unit tests to start processes and move them along their paths. Add the following references:

  • System.Configuration
  • SourceCode.Workflow.Client
  • SourceCode.Workflow.Management
  • SourceCode.HostClientAPI
  • SourceCode.Data.SmartObjectsClient
  • Microsoft.VisualStudio.QualityTools.UnitTestFramework.dll (found under c:\Program Files (x86)\Microsoft Visual Studio 10.0\Common7\IDE\PublicAssemblies)

Change the target framework to .NET Framework 4 in the project properties.

Create the test project

Add a test project to the solution (under Test Projects\Test Documents in the Add New Project dialog). Add a reference to the test framework class library project and to SourceCode.Workflow.Client.

Your Solution Explorer should look similar to this:

The framework project

The framework project contains:

  • ProcessHelper: a helper class with utility functions for common tasks in unit tests. Pulling this code out of the tests makes them quicker to develop, easier to read, and focused on the scenario they are testing.
  • IProcessTest: an interface that test classes must implement to use the ProcessHelper.
  • TestScenarioContext: a simple data class that keeps the process context for a test scenario.

TestScenarioContext

Add an Entities folder to the project and add this class to it (change the namespaces to match yours). It tracks the process instance data of a test run.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using SourceCode.Workflow.Client;

namespace SourceCode.Examples.UnitTests.Framework.Entities
{
 public class TestScenarioContext
 {
 public ProcessInstance ProcessInstance { get; set; }
 public Guid TestInstanceId { get; set; }

 public long ProcessId
 {
 get
 {
 long id = -1;
 if (this.ProcessInstance != null)
 {
 id = this.ProcessInstance.ID;
 }
 return id;
 }
 }
 }
}

IProcessTest

Add an Interfaces folder and add this interface. Test classes pass themselves into the ProcessHelper through it, so the helper can work with the process instance and other process data.

namespace SourceCode.Examples.UnitTests.Framework.Interfaces
{
       public interface IProcessTest
       {
              TestScenarioContext TestScenarioContext { get; set; }
              TestContext TestContext { get; set; }
              string ProcessName { get; }
       }
}

ProcessHelper

The ProcessHelper class provides helper methods for starting and working with processes and activities. It reads its connection strings from app settings and has methods to start and stop a process, get a worklist (for the current user or an impersonated one), action a worklist item, check that an activity executed, and build a folio for the test. Here are the two methods that do most of the work: starting a process, and checking an activity ran by querying the K2 reporting SmartObjects.

public static void StartProcess(IProcessTest testClass, Dictionary<string, string> dataFields, bool sleep)
{
 ConnectionSetup connSetup = new ConnectionSetup();
 connSetup.ConnectionString = ConnectionString;
 using (Connection conn = new Connection())
 {
 conn.Open(connSetup);
 ProcessInstance instanceToStart = conn.CreateProcessInstance(testClass.ProcessName);

 if (dataFields != null)
 {
 foreach (KeyValuePair<string, string> field in dataFields)
 {
 instanceToStart.DataFields[field.Key].Value = field.Value;
 }
 }

 instanceToStart.Folio = GetFolio(testClass);

 conn.StartProcessInstance(instanceToStart, true);

 testClass.TestScenarioContext.ProcessInstance = instanceToStart;
 }

 if (sleep)
 {
 System.Threading.Thread.Sleep(2000);
 }
}
public static bool EnsureActivityExecuted(IProcessTest testClass, string activityName)
{
 bool executed = false;
 string query = "select * from Activity_Instance.List where ProcessInstanceID = " + testClass.TestScenarioContext.ProcessId.ToString();
 using (SOConnection soConn = new SOConnection(SOConnectionString))
 using (SOCommand command = new SOCommand(query, soConn))
 using (SODataReader reader = command.ExecuteReader(CommandBehavior.CloseConnection))
 {
 soConn.Open();
 while (reader.Read())
 {
 string executedActivityName = reader["ActivityName"].ToString();
 if (executedActivityName.Equals(activityName))
 {
 executed = true;
 break;
 }
 }
 }

 return executed;
}

The full ProcessHelper listing is in the original post.

Configure the test project

You can give a unit test project its own configuration file by naming it <ProjectName>.dll.config. For a project named MyCompany.UnitTests.Process you would add MyCompany.UnitTests.Process.dll.config. Add it as an Application Configuration File and put the K2 connection settings in appSettings, changing the server names and ports to match your environment:

<appSettings>
              <add key="K2WorkflowServer" value="dlx"/>
              <add key="K2WorkflowServerPort" value="5555"/>
              <add key="K2SOConnectionString" value="Integrated=True;IsPrimaryLogin=True;Authenticate=True;EncryptedPassword=False;Host=dlx;Port=5555"/>
              <add key="K2WorkflowServerConnectionString" value="Integrated=True;IsPrimaryLogin=False;Authenticate=True;EncryptedPassword=False;Host=localhost;Port=5252"/>
              <add key="K2ManagementServerConnectionString" value="Integrated=True;IsPrimaryLogin=True;Authenticate=True;EncryptedPassword=False;Host=localhost;Port=5555"/>
       </appSettings>

There is also a K2WorkflowServerConnectionStringImpersonate key, a workflow server connection string with the domain, user ID and password of an account allowed to impersonate users. Set the username and password for your own environment.

The configuration file needs to be in the same directory as the dll when it runs. To automate this, open the test project properties, go to the Build Events tab and add this to the post-build event command line:

copy "$(ProjectDir)*.config" "$(TargetDir)"

Now every time the project is built, it copies the configuration file to the output directory.

Best practices

Scenario vs. method paradigm shift

In a typical unit test paradigm there is a one-to-one mapping between a class in the code library and a class in the unit test library, and each test method performs a discrete test. That is hard to apply to a K2 process. A process has to be started before you can test anything inside it, and if you need to test an activity ten steps in, the test first has to start the process and action the first nine steps.

So most unit tests for K2 processes are scenario based. A scenario generally tests one use case: for instance, one scenario tests an approval at the tenth step and a different scenario tests a denial at the tenth step. Use one class per scenario. That keeps the code easier to read and maintain, because the code that moves the process along can live in the class without name clashes across scenarios.

Helper classes take care of the common steps: starting a process, getting a worklist item, actioning it, updating a data field and so on. Many scenarios are very similar, with perhaps only one activity having a different outcome, so this saves a lot of repetition.

Use data fields to test line rules

Line rules can be tested by passing in data field values that exercise both the execution path and the non-execution path. Setting data fields when the process starts is the most common approach, but you can change a data field at any point mid-process if you need to.

Use the worklist to test task assignments

The worklist API can retrieve the worklist items for a process so you can check the right items were created and assigned to the right people. It can also execute a worklist item with an action, to test that the process correctly moves on to the next activity.

Use the K2 reporting SmartObjects to test activity execution

The client API doesn’t expose the list of activities that have executed for a process, but the K2 Workflow Reports SmartObjects do. EnsureActivityExecuted above reads it with a SmartObject ADO query.

Use XML files to simulate InfoPath form submission

InfoPath forms are just XML documents, so you can simulate a form submission by saving different versions of the form XML as files in the test project and passing them to the K2 InfoPath service.

Use SmartBox SmartObjects to simulate external systems

SmartObjects sit between the process and the system where the data actually lives, which gives you a chance to swap out the physical layer when it isn’t feasible to run automated tests against an external system. For example, your organisation may only have QA and production HRIS environments and may not want unit tests running against QA. You can configure the SmartObjects to use a SmartBox back end for the tests, much like mock objects in traditional unit testing, without changing the process itself.

Give process rights to the build process

The account the automated tests run under needs rights to start the processes. This only has to be done once, after the process is first deployed to the development server, either manually or as a step in the build script.

How-tos

Start a process

Every test scenario needs to start a process. ProcessHelper has several overloads. To start a process with data fields, use the overload that takes a string dictionary:

Dictionary<string, string> dataFields = new Dictionary<string, string>(1);
dataFields.Add("lineRuleField", "Go");

ProcessHelper.StartProcess(this, dataFields);
Assert.IsNotNull(this.TestScenarioContext.ProcessInstance, "Unable to start process.");

Depending on the horsepower of the development machine, the process can take a while to start. If it takes longer to start than your test takes to reach its next step, the test fails because the process instance isn’t there yet. So StartProcess sleeps the thread for two seconds by default. You can turn this off by passing false to the overload with the sleep parameter.

Get the worklist and action an item

GetWorklist retrieves all the active worklist items for the process, either for the current user or for a user you pass in. ActionWorklistItem actions an item with the action name you give it. A test typically checks the worklist has a task for the right user, actions it, then checks the right branch executed:

Worklist activeWorkListItems = ProcessHelper.GetWorklist(this, @"denallix\chad");

// in this process there should only be one active worklist item
Assert.AreEqual<int>(1, activeWorkListItems.Count);

// the user for this task should be chad
Assert.AreEqual<string>(@"k2:denallix\chad", activeWorkListItems[0].AllocatedUser.ToLower());

ProcessHelper.ActionWorklistItem(this, activeWorkListItems[0], "Approve");

bool approveBranchExecuted = ProcessHelper.EnsureActivityExecuted(this, "Approve Branch");
Assert.IsTrue(approveBranchExecuted, "Approve Branch did not execute");

Ensure an activity executed

EnsureActivityExecuted returns true if the named activity executed and false if it didn’t. Sometimes the test has to wait for K2 to write the activity to the logs, so ActionWorklistItem also sleeps for two seconds. If you aren’t using ActionWorklistItem and your test says the activity didn’t execute, sleep the thread before calling EnsureActivityExecuted.

Scenarios for testing the sample process

Each scenario is its own test class implementing IProcessTest, with a TestInitialize method that creates a new TestScenarioContext with a fresh TestInstanceId, and a TestCleanup that clears it. The test methods are:

  • Approve: start the process, check there is one task and that it’s Chad’s, approve it, then check the approve branch executed and the deny branch didn’t.
  • Deny: the same, but deny the task and check the deny branch executed and the approve branch didn’t.
  • Rework: Chad actions the task as Rework, the administrator gets a task and resubmits it, and then Chad should have a task again. This one doesn’t test the approve or deny branches.
  • Line rule equals Go: start the process with lineRuleField set to ‘Go’ and check the Line Rule Activity executed.
  • Line rule equals Stop: start with ‘Stop’ and check the Line Rule Activity did not execute.

Here is the approve scenario test method:

[TestMethod]
public void TestApproveScenario()
{
       ProcessHelper.StartProcess(this);
       Assert.IsNotNull(this.TestScenarioContext.ProcessInstance, "Unable to start process.");

       Worklist activeWorkListItems = ProcessHelper.GetWorklist(this, @"denallix\chad");

       // in this process there should only be one active worklist item
       Assert.AreEqual<int>(1, activeWorkListItems.Count);

       // the user for this task should be chad
       Assert.AreEqual<string>(@"k2:denallix\chad", activeWorkListItems[0].AllocatedUser.ToLower());

       ProcessHelper.ActionWorklistItem(this, activeWorkListItems[0], "Approve");

       bool approveBranchExecuted = ProcessHelper.EnsureActivityExecuted(this, "Approve Branch");
       Assert.IsTrue(approveBranchExecuted, "Approve Branch did not execute");

       bool denyBranchExecuted = ProcessHelper.EnsureActivityExecuted(this, "Deny Branch");
       Assert.IsFalse(denyBranchExecuted, "Deny Branch executed when it should not have");
}

The full listings for all five scenario classes are in the original post.

In my next how-to I will be looking at how to use SpecFlow to make testing a workflow more readable to the business.