We´d like to unit test everything but sometimes that´s just not enough. Especially when working with third-party libraries which output files of some kind and we need to verify the result.
We could use something like this to get a unique name for our temporary test output:
File.WriteAllText(System.IO.Path.GetTempFileName(), "blah blah");
Problem is, what if your test fails and you want to check your file? Yes, you might be able to intercept the test with the debugger and verify the contents before writing but suppose your output is a complex HTML or even docx? That’s not a joy to interpret in the QuickWatch window.
Instead, use this and you´ll get a dynamic output name directly connected to the test name:
public class MyTest { /// <remarks>The test context is automatically set by MSTest framework</remarks> public TestContext TestContext { get; set; } [TestMethod] public void MyTest () { File.WriteAllText (GetType ().Name + " - " + TestContext.TestName + ".docx", "contents"); } }
I´ve found that using the TestContext this way proves to be quite useful and I think that if someone else were to examine your test results after you, they´d be happy to find named output files.