Load file during Unit Test
Using Unity 2018.1.1f1 and Visual Studio Community 2017
I've been creating unit tests using unity's built in Test Runner. In this particular unit test, I want to read a file's content into a string. Without having to build a static path to the file (which will sit next to the unit test class itself), how can I reference it?
The folder structure looks like this:
Directory:
Assets/Plugins/MyTools/Common/Properties/_tests/
Files:
MyTools.Common.Properties.Tests.asmdef
PropertiesTests.cs
test.txt
test-prop-file.txt
The test and some output details:
namespace MyTools.Common.Properties.Tests {
public class PropertiesTests {
[Test]
public void ParsePropsFile() {
Debug.Log(Assembly.GetExecutingAssembly().GetName());
// MyTools.Common.Properties.Tests, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null
Debug.Log(GetType().Assembly.GetManifestResourceNames().Length);
// 0
Debug.Log(Assembly.GetExecutingAssembly().GetManifestResourceNames().Length);
// 0
}
}
}
In visual studio, I've tried to set the properties (Build Action = Embedded Resource, and Copy to Output Directory = Copy Always) of test-prop-file.txt and test.txt but they do not seem to do anything. Also, when I close VS and reopen it, these are set back to what they were before (None and Do Not Copy). I've also tried other combos like Build Action = Resource or Content but still nothing.
So how can I go about loading these files in the unit test without referencing them directly with a static path like D:/Code/Unity/MyProject/Assets/Plugins/MyTools/Common/Properties/_tests/test.txt?
Answer by Valthec · Apr 03, 2020 at 08:41 AM
I know that is an old question but there are not many answers to this problem so I want to save some time to others. It is only workaround but it solves my problem. Its goes up two folders from location where test are run "Library\ScriptAssemblies\" to the Assets folder and then to the place where my text file is stored. Hope this help!
string cofigPath = Path.GetFullPath(Path.Combine(TestContext.CurrentContext.TestDirectory, "..", "..", @"Assets\Tests\TestData\config.json"));
Credits belongs to Maxime: https://stackoverflow.com/questions/51391472/load-file-during-unit-test-in-unity3ds-unity-test-runner#comment97228624_51391472
Your answer
Follow this Question
Related Questions
Can i run tests in Unity test runner without creating asmdef files? 0 Answers
Unit test: PlayerPrefs, Attempted to access a missing method. 1 Answer
Testing on Genymotion: Grey Scene except Canvas items 1 Answer
Instantiating prefab causes assembly load error in unit test 0 Answers
export unity file into .bin 0 Answers