Wednesday, 2 May 2012

Unit test of workflow for code action

Unit testing workflow code action


As part of my recent project I needed to do unit testing of a project. I have read article http://msdn.microsoft.com/en-us/magazine/dd179724.aspx#id0400009. This does not seem to be too bad, but it does not fit with my requirement.

I have created a CodeActivity for which I need to create unit test.

For our purpose I have created simple activity to do simple math. Pass two parameters and return result.

public sealed class ParameterActivity : CodeActivity
    {
        public InArgument<int> Argument1 { getset; }
        public InArgument<int> Argument2 { getset; }
        public OutArgument<int> Result { getset; }
 
        protected override void Execute(CodeActivityContext context)
        {
            int a = context.GetValue(Argument1);
            int b = context.GetValue(Argument2);
 
            context.SetValue(Result, a + b);
        }
    }


I have added this into my workflow and as good developer, I want to verify that my code works as expected and therefore i want to create a unit test for this.

Great, right button on the method and generate unit test for this method.
you will get generated code as follows.

ParameterActivity_Accessor target = new ParameterActivity_Accessor(); // TODO: Initialize to an appropriate value
CodeActivityContext context = null// TODO: Initialize to an appropriate value
target.Execute(context);
Assert.Inconclusive("A method that does not return a value cannot be verified.");

Little of background.

Every action is component itself and you can add them into workflow or sequence, but any action can be stand alone.

Therefore I have made decision to progress to invoke workflow on only the action.
using Workflow Invoker and setting parameters to this action.

Now I know that results of Invoke will return results (if the action contains) which I can access using array.
Every result has pair <string, object>.
Now we know enough to create our test.

var results = WorkflowInvoker.Invoke(new ParameterActivity() {Argument1 = 2, Argument2 = 2});
int val;
 
int.TryParse(results["Result"].ToString(), out val);
            
Assert.AreEqual(val, 4);


Now you can try this, and let me know how you get on.