48

With NUnit, if you add Debug.Print statements in your tests they appear in the test output. (At least they do in the ReSharper unit test window.)

When using a NAnt build file that executes the same tests, those Debug.Print statements do not appear.

How can I add messages to my unit tests that will appear both in the NUnit output and the build log output from NAnt?

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
The Evil Greebo
  • 7,013
  • 3
  • 28
  • 55

2 Answers2

64

NUnit 3's way of logging during a test is via the TestContext class. It has a raft of static Write variants. Each emits general content to the test result.

TestContext.Out yields a TextWriter that can also be used to emit logging information into test results.

Peter Mortensen
  • 30,738
  • 21
  • 105
  • 131
Randy Larson
  • 6,817
  • 2
  • 18
  • 13
  • 3
    Is there a solution for NUnit 2? – Ryan Leach May 11 '18 at 07:43
  • Is this any different from calling `Console.WriteLine()`? Does the message get embedded in the test result? Sorry for the lazy asking -- trying to build a testrunner with NUnit.Engine and wondering if I can capture notes like these within the output XML. I will experiment. – alelom Feb 17 '23 at 13:32
39

Console.WriteLine() should be preserved (it is for my version of NUnit at least).

That said, consider - each time you want to add some text output - how you could turn it into an assertion with a message. Your tests will get much better.

skolima
  • 31,963
  • 27
  • 115
  • 151
  • 2
    Generally I would agree with you, but in this case the information needed wasn't related to testing the app, it was metadata related to running the tests (specifically the executing path). – The Evil Greebo Oct 24 '12 at 18:14
  • 1
    Using Resharper + NUnit 2 you occasionally get interleaved results, or missing text at the end. – Ryan Leach May 11 '18 at 07:42