3

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 :(

Community
  • 1
  • 1

2 Answers2

2

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());
Community
  • 1
  • 1
Alexei Levenkov
  • 98,904
  • 14
  • 127
  • 179
  • See example of TraceListener that simply appends trace messages to a string at [Trace listener to write to a text box (WPF application)](http://stackoverflow.com/a/1389289) – Michael Freidgeim Jul 05 '16 at 07:49
1

You need to use Console.WriteLine for the output to show up in the test runner. However, this is a bad thing. I recommend using a logging framework like nlog.

jonnii
  • 28,019
  • 8
  • 80
  • 108