Reputation: 915
I have a unit test project and library project. I want to use the pdf file in library project as template. When I use Environment.CurrentDirectory I get path of the unit test project, but I want to get the path of the library project to reference pdf file.
Path.Combine(Environment.CurrentDirectory, "../PDFs/template.pdf");
What is the equivalent statement to get path to file in library project when executing the unit test?
Upvotes: 10
Views: 8755
Reputation: 171
It is possible to get the source directory of a project using [CallerFilePath]
.
I usually do something like this:
internal static class ProjectSource {
private static string CallerFilePath( [ CallerFilePath ] string? callerFilePath = null ) =>
callerFilePath ?? throw new ArgumentNullException( nameof(callerFilePath) );
public static string ProjectDirectory() => Path.GetDirectoryName( CallerFilePath() )!;
}
Then from your tests you can do ProjectSource.ProjectDirectory()
to obtain the project root. This should be used with care however. I mostly use this to read test data files to avoid copying them to bin.
Note that this can be used across projects as well if you make the change from internal
to public
but that could be considered bad practice.
Upvotes: 4
Reputation: 61339
You can't. The unit test project has a copy of the referenced assembly in its bin
folder and that doesn't know about the original "source" location (nor should it).
Unit tests should be able to execute in a vacuum, not relying on something to exist elsewhere in the filesystem (or ideally not rely on the filesystem or other external resources at all).
The only way to solve the problem as posited is to ensure that your "template.pdf" is copied to the output directory of the unit test, probably with a post-build step. A much better approach would be to just include the template in the unit test project.
Upvotes: 5