使用NUnit进行单元测试时获得所需/正确的装配路径

now*_*ed. 12 c# nunit unit-testing shadow-copy .net-4.5

我刚刚开始尝试使用moq对我的模块进行单元测试.

实际上,我必须编写单元测试的类使用

Assembly.GetExecutingAssembly().Location 在内部确定路径.

但是,这在编写单元测试时不起作用,因为执行程序集的路径不同(采用单元测试程序集的路径)

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

我试过,禁用阴影复制.

AppDomainSetup appDomain= new AppDomainSetup{ShadowCopyFiles = "false",};
appDomain.ShadowCopyFiles=false.ToString();
Run Code Online (Sandbox Code Playgroud)

不过,它不起作用!

任何建议表示赞赏.提前致谢.

Jef*_*wis 15

你可以使用TestContext.CurrentContext.TestDirectory NUnit的Charlie Poole在这里提到的.

参考:https://stackoverflow.com/a/29057351/589574


Chr*_*tle 8

也许不是你的问题的确切答案,但就个人而言,我甚至不会尝试Assembly.GetExecutingAssembly().Location在单元测试中获得实际值.我会创建这样的东西:

public interface IAssemblyHelper
{
    string GetLocationOfExecutingAssembly();
}

public class AssemblyHelper : IAssemblyHelper
{
    public string GetLocationOfExecutingAssembly()
    {
        return Assembly.GetExecutingAssembly().Location;
    }
}
Run Code Online (Sandbox Code Playgroud)

在运行时,我会注入AssemblyHelper需要它的类的构造函数,如IAssemblyHelper.在单元测试中,我会模拟IAssemblyHelper,设置它以返回预期的路径,并将模拟传递给类的构造函数.

测试代码与应用程序中实际执行程序集的位置路径一起工作应该是验证测试的一部分.


小智 5

我的同事建议了以下适用于我们所有用例的解决方案:

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);
    }
}
Run Code Online (Sandbox Code Playgroud)


now*_*ed. 3

最后我是通过这样的方式完成的:

我使用了 NUnit 框架并在 NUnit 中禁用了卷影复制。在调用单元测试库的目录中创建了我的配置文件的副本。

因此,每当调用我的单元测试(例如从路径“A”)时,我的应用程序都不会抱怨该位置没有配置文件,因为我将配置文件放在路径“A”中。

(ps:我之所以获取程序集位置是为了能够在该位置找到我的配置文件)

[整个想法是这样的:通过卷影复制,装配路径是动态的。禁用它并且程序集路径是静态的]