Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unit testing of WF code activity

I have created coded activity and now I want to unit test it, but I do not know how. Any example will be appreciated.

My simple example is below.

  public sealed class ParameterActivity : CodeActivity
{
    public InArgument<int> Argument1 { get; set; }
    public InArgument<int> Argument2 { get; set; }
    public OutArgument<int> Result { get; set; }

    protected override void Execute(CodeActivityContext context)
    {
        var a = context.GetValue(Argument1);
        var b = context.GetValue(Argument2);

        context.SetValue(Result, a + b);
    }
}
like image 962
cpoDesign Avatar asked May 02 '12 21:05

cpoDesign


1 Answers

First of all, in case your activity returns a single value, just inherit from CodeActivity<TResult> and easily override Execute() with TResult as return type. Moreover, you've already available an OutArgument<TResult> Result.

public sealed class ParameterActivity : CodeActivity<int>
{
    public InArgument<int> Argument1 { get; set; }
    public InArgument<int> Argument2 { get; set; }

    protected override int Execute(CodeActivityContext context)
    {
        var a = Argument1.Get(context);
        var b = Argument2.Get(context);

        return a + b;
    }
}

That being said, WorkflowInvoker is the way to go to unit test almost all your activities. Taking above custom code activity as example:

[TestFixture]
public sealed class ParameterActivityTests
{
    [Test]
    public void ParameterActivity_Test()
    {
        var activity = new ParameterActivity();

        var input1 = new Dictionary<string, object> 
        {
            { "Argument1", 10 },
            { "Argument2", 5 }
        };

        var input2 = new Dictionary<string, object> 
        {
            { "Argument1", -13 },
            { "Argument2", 3 }
        };

        var output1 = WorkflowInvoker.Invoke<int>(activity, input1);
        var output2 = WorkflowInvoker.Invoke<int>(activity, input2);

        Assert.That(output1, Is.EqualTo(15));
        Assert.That(output2, Is.EqualTo(-10));
    }
}

Rather than WorkflowInvoker you can also use WorkflowApplication but for unit testing that doesn't seem at all necessary when you just want to quickly invoke short-lived workflows for them to do "their thing" and return. Unless you want to test more elaborate stuff like asynchronous workflows and/or bookmarks.

You'll also want to check Microsoft.Activities.UnitTesting.

like image 176
Joao Avatar answered Oct 13 '22 10:10

Joao