I have some code that I need to see when I am running a test, and TestContext would have to be part of my Test class I need the debug.writelines of the class being tested displayed. I considered just passing a TestContext to my MessageStatus static method and may have to but that will be a PITA because the UnitTest class would have to pass the TestContext to the object it is testing. Too tightly coupled for my taste.
In basic terms
[TestMethod]
public void TestA()
{
//....
Assert.IsTrue(Blah.Blah()));
}
public void Blah()
{
Debug.WriteLine("Hello");
}
never shows up when I run the unit tests!
I could change it to:
TestContext t;
[TestMethod]
public void TestA()
{
//....
Assert.IsTrue(Blah.Blah(t)));
}
public void Blah(TestContext p1)
{
p1.WriteLine("Hello");
}
but that is insane it means changing all my signatures and tight coupling. I read the thread at How to write output from a unit test? it does not help :(
If you need to see lines produced by Debug.WriteLine or deal with assertions produced by Debug.Assert you can create your own System.Diagnostic.TraceListener to redirect output to TestContext - see my answer What do I have to do so that assertions won't block automated tests anymore?.
public class MyListenerThatDoesNotShowDialogOnFail:
System.Diagnostics.TraceListener
{
// This is to avoid message box on Debug.Assert(false);
public override void Fail(string message, string detailMessage)
{// do something UnitTest friendly here like Assert.Fail(false)
}
// This (+Write) is to redirect Debug.WriteLine("Some trace text");
public override void WriteLine(string message)
{// do something UnitTest friendly here like TestContext.Write(message)
}
}
Somewhere in the test setup listener. Note that sample below is simplified, you probably want to save current listeners and restore at the end of test.
Debug.Listeners.Clear();
Debug.Listeners.Add(new MyListenerThatDoesNotShowDialogOnFail());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With