Search code examples
c#.netunit-testingassembly-loading

How to find physical path inside of a C# .NET integration test at runtime?


In order to wrap an integration test around an old legacy process that builds detailed files based on certain inputs, I have the need to dynamically load a DLL by providing the full path to the file.

This test will run on many different developers' machines which do not always share the same physical application directory, but will also run on many servers as it makes its way through a Continuous Integration process, and sometimes multiple instances of the application will be running on the same physical machine. The point is, there's no standard path that can be relied upon to hardcode into this test. What I really need is some mechanism that can tell me the physical path that the test is executing under at the time that it is executing, and then I can use a relative path from there to always reliably find the DLL in the application's installation.

Since this is in a test, I cannot rely on something like HttpContext.Current.Server.MapPath() or Request.ApplicationPath, since Current will be null when the test runs.

Short of writing a hack to deploy the DLL I need to load dynamically to a special folder on the root of any drive that might build and run the application, does anyone know a good .NET strategy to find the physical path of the test at runtime?

I'm using NUnit in a C# Web application, along with Approval Test style assertion, so a simple test that would need to do this would look like this:

[Test]
public void ShouldGenerateFileConsistently()
{
    string pathToDll = FindRelativePathToDllBasedOnPhysicalPath(); // <-- what I need to figure out

    string generatedFileContents = OutputManager.GenerateReportUsingDynamicDll(pathToDll);

    Approvals.Verify(generatedFileContents);
}

Solution

  • var codebase = Assembly.GetExecutingAssembly().CodeBase;
    var pathUrlToDllDirectory = Path.GetDirectoryName(codebase);
    var pathToDllDirectory = new Uri(pathUrlToDllDirectory).LocalPath;