jeudi 24 janvier 2019

Unexpected Location pf Assembly.GetExecutingAssembly When NUnit Runs Multiple Assemblies

I recently encountered an odd issue when performing unit tests. My solution contains a helper class with a property for getting the directory of the executing assembly. It looks like this:

public static class DirectoryHelper
{
    public static string ExecutingAssemblyDirectory
    {
        get
        {
            var codeBase = Assembly.GetExecutingAssembly().CodeBase;
            var uri = new UriBuilder(codeBase);
            var path = Uri.UnescapeDataString(uri.Path);
            return Path.GetDirectoryName(path);
        }
    }
}

This method is called through various test classes to get relative file paths to dependent resources.

Take the following contrived projects as examples:

TestProject1.dll - TestFixture1.cs

[TestFixture]
public class TestFixture1
{
    [Test]
    public void VerifyExecutingAssemblyDirectory1()
    {
        StringAssert.Contains(@"\TestProject1\bin\Debug", 
        DirectoryHelper.ExecutingAssemblyDirectory);
    }
}

TestProject2.dll - TestFixture2.cs

[TestFixture]
public class TestFixture2
{
    [Test]
    public void VerifyExecutingAssemblyDirectory1()
    {
        StringAssert.Contains(@"TestProject2\bin\Debug", 
        DirectoryHelper.ExecutingAssemblyDirectory);
    }
}

When these tests are ran individually they pass and the location of the returned assembly is the debug folder of the test class.

However, when ran together, TestFixture2.VerifyExecutingAssemblyDirectory2() is actually returning the path to the bin folder of TestProject1, rather than TestProject2.

I'm trying to determine why this behavior is happening and understand a better way of going about this. I've found that using .GetCallingAssembly will resolve this problem, but it doesn't seem like I should have to do this.

I've created an example to reproduce this issue and posted to GitHub. TylerNielsen/NUnitExecutingAssemblyExample





Aucun commentaire:

Enregistrer un commentaire