I am new to c# and unit testing. I have a config file stored in Source folder(on Server). I need to read that file in my Unit test class. This will be running on build server so need to find out a way of working out. Something like GetExecutingAssembly
CodePudding user response:
Add the file to the same project, preferably in a data folder or something like that.
Right click the file in visual studio and select properties, build action set to embedded resource
depending on how defensive you want you load, do something like
using var stream = Assembly .GetAssembly(this.GetType()) .GetManifestResourceStream("<mynamspecase>.<myfilename>.<ext>"); Assert.NotNull(stream); var reader = new StreamReader(stream); string serialized = reader.ReadToEnd(); var dto = System.Text.Json.JsonSerializer.Deserialize<myfiletype>(serialized); Assert.NotNull(dto);
Or if not wanting to bring your config to an unknown test server ... but looking blindly offset where you are for some reason, you could use the where you are as a navigation point.
string[] pathParts =
Assembly.GetAssembly(this.GetType()).Location.Split(@"\");
//Go to party
// now your text assembly is in last position, you will not be looking for that
pathParts[pathParts.GetUpperBound(0)] = "";
string basePathWhereWeExecute = string.Join(@"\", pathParts);
var di = new DirectoryInfo(basePathWhereWeExecute);
//You can combine, just jump up and down the path and use the following
FileInfo[] whatFilesAreThere = di.GetFiles();
DirectoryInfo[] whatDirectoriesAreThere = di.GetDirectories();
// I'd suspect you can get more info that just anywhere with a name if it's legit with somebody wanting you to succeed :D
CodePudding user response:
Are you using NUnit, MSTest, or something else as your test framework? You can get the directory of your unit test dlls using NUnit's TestContext.TestDirectory or MSTest's TestContext.TestRunDirectory. Then I'd add the config file to the test project, and set it to copy to output directory. If the config is somewhere else in your repo tree, maybe add to your test project as a linked file.