How to set test file path for MbUnit tests with Gallio via NAnt?

522 views Asked by At

Please excuse the ambiguous title; it's difficult to describe in a single line.

Basically we have MbUnit tests which run fine using TestDriven from within Visual Studio, but fails when attempting to run the tests via the <gallio> task from within NAnt.

The failure are to do with the tests which attempt to read files; they read files relative to the current directory, for example "..\..\files\dir\whatever". However the problem seems to be that Gallio copies the test DLLs to a directory elsewhere, and sets the current directory to be "%HOMEDIR%\AppData\Local\Temp\Gallio\MSTestAdapter\randomname\TestDir\Out\something".

So my question is two-fold: Where should I be putting files which are required by tests so they can be found at runtime, and how should I be referring to them from code?

(Also, I didn't think we were using MS-Test at all, so how come there's an 'MSTest' directory in there?)

1

There are 1 answers

1
The Chairman On BEST ANSWER

Although we use NUnit instead of MbUnit I think there is some general advice I can give regarding handling files in unit tests.

Never rely on paths - neither absolute nor relative. Keep control over paths inside your tests. This is what we do:

  1. Add a folder named Resources to your test project (so you have everything in one place)
  2. Put required files in there (e.g. MyFile.txt)
  3. Add the files to your project via Add > Existing Item... (so your files are kept with your sources. They get deployed afterwards as part of the assembly of your test project)
  4. Add the files to your test project's resources (tab Resources in the project's properties, Add Resource > Add Existing File...)
  5. Use the file in your test fixture:
    1. Define a file path field in your fixture class (use Path.GetTempFileName() since you have a unique path then and it's most likely you have sufficient access rights on any machine)
    2. Create a local file using the file path during test setup
    3. Use the file in your test
    4. Delete the created file during tear down

Here is a sample:

[TestFixture]
public class MyFixture
{
  private static readonly string MyFilePath = Path.GetTempFileName();

  [SetUp]
  public void SetUp()
  {
    // use File.WriteAllBytes for binary files
    File.WriteAllText(MyFilePath, Properties.Resources.MyFile);
  }

  [Test]
  public void TestSomething()
  {
    Assert.That(ObjectUnderTest.UseFile(MyFilePath), Is.True);
  }

  [TearDown]
  public void TearDown()
  {
    File.Delete(MyFilePath);
  }
}