13

I'm using Microsoft Visual Studio Test Framework and some of my tests require an xml file as input. Currently I've placed them under a Resource directory in my TestProject and I'm accessing them via a "..\..\whatever" path Name. I would like an advice for a good practice when using test resource files as I would like to reuse my test in all this situations - Directly from VS 2010 - During my build process on the server - In a Continuous Integration environment in a transparent (and simple) way.

Terenzio Berni
  • 485
  • 1
  • 4
  • 12

5 Answers5

14

First of all I typically try to reduce the need to rely on the file system at all during testing (by introducing some sort of abstraction for the file system, so that the file system access can be mocked).

If that is not possible, I include such files in the test project, in a sub folder called TestData or something similar. Then I set the the "Copy to Output Directory" to "Always Copy", so that the file is included in the output, and at a location that is known in relation to the test assembly (regardless of whether the build is done inside Visual Studio or on a build server). This works very well as long as no code under test is modifying files, but only needs them for reading data.

Fredrik Mörk
  • 155,851
  • 29
  • 291
  • 343
  • 1
    Where do you set Copy to Output Directory to Always Copy? On every file or you can set it globally on a directory? – Terenzio Berni Apr 08 '11 at 12:05
  • @Terenzio: you need to set it on the individual files, I think. I think you can do that in one take though by selecting a range of files in the Solution Explorer (can't check now: don't have Visual Studio around right now). – Fredrik Mörk Apr 08 '11 at 12:36
  • 2
    VS2010: Also set Build Action file property to "None". – Dmitry Jun 16 '11 at 07:35
4

I would suggest the approach from the following answer. It's a similar question. This approach makes use of the DeploymentItem attribute, also used when doing data driven unit testing.

Community
  • 1
  • 1
0

I do something like this in one of my integration tests; and I've solved it in the same way you have. As long as your file is checked into source control, and you use a relative path (which it looks like you are), it should work as expected.

Tejs
  • 40,736
  • 10
  • 68
  • 86
0

We are using TFS2010 for CI. All the output file placed into Binaries folder. For the config resource like XML we used use Copy to output directory option as Copy always. So it will be placed in to the output directories always.

Anuraj
  • 18,859
  • 7
  • 53
  • 79
0

I included this in my UnitTest project file.

<ItemGroup>
    <Content Include="Resources\**" />
</ItemGroup>

Then I see it included in the .\bin\Debug\net6.0-windows10.0.19041.0\UnitTest\ directory after building. Last, I use huseyint's answer to get to the file I need.

Luyang Du
  • 160
  • 1
  • 10