How can I access TestMethod parameters from a TestCleanup method with MSTest

Viewed 82

I have some test methods in my MSTest project that accept parameters from a DataRow. I was hoping that there would be some way to get access to those parameters in a TestCleanup method, but I haven't found a good way to do it.

I started looking into using the TestContext object, but the DataRow property of that object seems to be used for some other purpose.

Currently I'm using a property in my test class to hold the value, but it seems to me that there should be a better way. Any ideas?

Here's an example of what I currently have.

[TestClass]
public class ExampleTestClass
{
  //This property stores the value so I can use it in TestCleanup
  private static string _filename;

  public TestContext TestContext { get; set; }

  [TestMethod]
  [DataRow("filename_for_test")]
  public void CanDoSomethingWithAFile(string filename)
  {
    //Store the test parameter in the property for use in TestCleanup
    _filename = filename;
    //The rest of the test ...
  }

  [TestCleanup]
  public void CleanupTest()
  {
    //If the test passes, I want to clean up any files that the test created.
    if(TestContext.CurrentTestOutcome == UnitTestOutcome.Passed)
    {
      //Call a method that deletes any files that were created during the test run.
      //The files use the value stored in _filename when they are created, so 
      //I can use the value of _filename to find the files I need to delete
      TryToDeleteTestFiles(_filename));
    }
  }
}
0 Answers
Related