4

consider the following test class:

[TestClass]
public class ExampleTests
{
    [TestMethod]
    public void FileDoesNotExists()
    {
        Assert.IsFalse(System.IO.File.Exists("testfile.txt"));
    }

    [TestMethod]
    [DeploymentItem("testfile.txt")]
    public void FileExists()
    {
        Assert.IsTrue(System.IO.File.Exists("testfile.txt"));
    }

}

Depending on the order in which these tests are run they might pass but since there is no guarantee that they will run in the order that they are defined the real world behavior is non-deterministic... obviously this is bad.

I have looked around and experimented with the TestCleanupAttribute but haven't been able to find a reliable way to get both tests to pass but it seems like there should be an easy method to do this. Does such a method exist?

update: This appears to be impossible because the test framework assumes that DeploymentItems do not change once deployed and therefore only deploys each item once. In the short term I have changed the code under test to no longer require this behavior, longer term I'll most likely implement an attribute that doesn't make this assumption.

Yaur
  • 7,333
  • 1
  • 25
  • 36

1 Answers1

2

DeploymentItems are actually the files that you would normally deploy to the client's computer, so you're not meant to remove them after you deploy them!

You should create a 'Sandbox' directory for your unit tests and use the normal .NET filesystem methods like File.Delete to do your file copy/access/delete stuff.

Maria Ines Parnisari
  • 16,584
  • 9
  • 85
  • 130
Teoman Soygul
  • 25,584
  • 6
  • 69
  • 80
  • The behavior I was attempting to test was the behavior when an (expected but not strictly required) configuration file was missing, but this behavior is also problematic in the case where different versions of the same item need to be deployed for different tests. A sandbox directory seems workable but not ideal since it increases the amount of boiler plate code required in each test. – Yaur May 18 '11 at 15:00
  • I somethimes offload such repeated file access code to a static class with static functions. I couldn't find a way around this with mstest buth xUnit.net seems to have an interesting interface. i.e. IUseFixture where you define DeploymentFixture youself for the class and run proper methods before each test. – Teoman Soygul May 18 '11 at 15:10