Question

I just started experimenting moq for unit testing my modules.

Actually, the class for which I have to write an unit test uses

Assembly.GetExecutingAssembly().Location internally to determine a path.

But, this doesn't work while writing unit tests because, the path of the executing assembly is different (the path of the unit testing assembly is taken)

AppData\\Local\\Temp\\3ylnx32t.ukg\\TestApplication.Test\\assembly\\dl3\\aeb938e6\\f3664631_d982ce01.

I tried, disabling shadow copying.

AppDomainSetup appDomain= new AppDomainSetup{ShadowCopyFiles = "false",};
appDomain.ShadowCopyFiles=false.ToString();

still, it doesn't work!

Any suggestions are appreciated. Thanks in advance.

Was it helpful?

Solution 4

Finally, I accomplished this through this way:

I used NUnit Framework and disabled Shadow copying in NUnit. Created a copy of my configuration file in that directory where the unit testing library is invoked.

So, whenever my unit test is invoked (say from path 'A'), my application doesn't complain that there is no configuration file in that location since i put my configuration file in path 'A'.

(ps: The reason why I get the assembly location is to be able to find my configuration file in that location)

[The whole idea is this: with shadow copying, the assembly path is dynamic. disable it and the assembly path is static]

OTHER TIPS

You can use TestContext.CurrentContext.TestDirectory as mentioned by Charlie Poole from NUnit here.

Reference: https://stackoverflow.com/a/29057351/589574

Perhaps not an exact answer to your question, but personally, I wouldn't even try to get the actual value of Assembly.GetExecutingAssembly().Location during a unit test. I'd create something like this:

public interface IAssemblyHelper
{
    string GetLocationOfExecutingAssembly();
}

public class AssemblyHelper : IAssemblyHelper
{
    public string GetLocationOfExecutingAssembly()
    {
        return Assembly.GetExecutingAssembly().Location;
    }
}

At runtime, I'd inject AssemblyHelper into the constructor of the class that required it, as IAssemblyHelper. In unit tests, I'd mock IAssemblyHelper, set it up to return an expected path, and pass the mock into the class's constructor.

Testing that the code works with an actual executing assembly's location path in your application should be part of an acceptance test.

My colleague suggested a following solution that works for all our use cases:

public static string AssemblyDirectory
{
    get
    {
        string codeBase = Assembly.GetExecutingAssembly().CodeBase;
        var uri = new UriBuilder(codeBase);
        string path = Uri.UnescapeDataString(uri.Path);
        return Path.GetDirectoryName(path);
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top