0

I'm new to Nunit3 and am currently using it to run some tests and want to read test data from a file rather than hardcoding it. The test data is used as the "expected" value and I want to read from a file because it is very large. Currently, reading from an absolute path works (ex: @"C:\path\to\TestData\testdata.txt"). However, this is hardcoded into the MyTest.cs test and I want it to be relative for testing on github actions or when testing on a different system. Is this possible?

I've tried to use things like "TestData\testdata.txt" but the testing context is different than the context in the source directory I believe and I get file does not exist errors. I have also tried to use Path.Combine() with Path.GetDirectoryName(Assembly.GetEntryAssembly().Location and System.Environment.CurrentDirectory but the directory is not there because it doesn't get copied during the test build so the final path is incorrect.

Thanks!

TestAPI
|
-- src
-- API.Tests (this is a folder)
  |
  -- MyTest.cs
  -- TestData
     |
     -- testdata.txt
usagibear
  • 303
  • 3
  • 12
  • Are you able to copy the text file to the output directory when the test project is compiled? – gunr2171 Aug 25 '22 at 19:21
  • You'd better not, as your test assemblies can be copied to a shadow folder without those files in certain cases. Try to embed those data files as resources so that your code can read from resources instead. – Lex Li Aug 25 '22 at 19:23
  • @LexLi How would I embed those data files as resources? Apologies for the dumb question. – usagibear Aug 25 '22 at 20:36
  • You might get started from https://learn.microsoft.com/en-us/dotnet/core/extensions/create-resource-files and Visual Studio actually makes it much easier to manage. – Lex Li Aug 25 '22 at 23:48

1 Answers1

1

It appears that a way to do this is to embed files directly into the *.csproj.

To do that, assuming your TestData is in the same directory as the *.csproj file, add the following to the *.csproj file between the <Project></Project> tags. This will copy all the files in the TestData directory into the build context.

<ItemGroup>
   <Content Include="TestData\*.*">
      <CopyToOutputDirectory>Always</CopyToOutputDirectory>
   </Content>
</ItemGroup> 

In your test code, you can access a file via the following, replace testdata.txt with your file name.

string path = Path.Combine(TestContext.CurrentContext.TestDirectory, @"TestData\testdata.txt");

Now you should be able to read data from that path now.

If there is a better way, please let me know. Thanks!

References

Thanks @lex-li and @gunr2171!

usagibear
  • 303
  • 3
  • 12