Question: Suppose you want to test an activity that uses WriteLine and you want to verify the output.  How do you do it?

Answer: Add a StringWriter to the Extensions collection before running your test

Testing this activity

image

Use this test

[TestMethod]

public void ShouldSayHelloWorld()
{

var wi = new WorkflowInvoker(new HelloWorld());

// The WriteLine activity will use an extension
// of type TextWriter instead of the Console
// if it finds one
var writer = new StringWriter();
wi.Extensions.Add(writer);

wi.Invoke();

Assert.AreEqual("Hello\r\nWorld\r\n", writer.ToString());
}

But… what if you had 100 lines of text?  It would get pretty tricky to deal with the writer text.  In that case, you could split the buffer into an array of strings using Regex which makes it much easier to work with.

[TestMethod]

public void ShouldSayHelloWorldUsingRegex()
{
var writer = new StringWriter();

var wi = new WorkflowInvoker(new HelloWorld());
wi.Extensions.Add(writer);

wi.Invoke();

// If you have a lot of text to verify
// splitting the writer into an array of strings
// makes it easier to deal with
string[] lines = Regex.Split(writer.ToString(), Environment.NewLine);

Assert.AreEqual(3, lines.Length);
Assert.AreEqual("Hello", lines[0]);
Assert.AreEqual("World", lines[1]);
// There is always 1 blank line at the end
Assert.AreEqual(string.Empty, lines[2]);
}