How to set test file path for MbUnit tests with Gallio via NAnt?
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 开发者_JAVA百科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?)
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:
- Add a folder named
Resources
to your test project (so you have everything in one place) - Put required files in there (e.g.
MyFile.txt
) - 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) - Add the files to your test project's resources (tab
Resources
in the project's properties,Add Resource
>Add Existing File...
) - Use the file in your test fixture:
- 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) - Create a local file using the file path during test setup
- Use the file in your test
- Delete the created file during tear down
- Define a file path field in your fixture class (use
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);
}
}
精彩评论