12

我刚刚开始尝试最小起订量来对我的模块进行单元测试。

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

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();

仍然,它不起作用!

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

4

4 回答 4

18

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

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

于 2015-03-15T04:53:48.163 回答
10

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

public interface IAssemblyHelper
{
    string GetLocationOfExecutingAssembly();
}

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

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

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

于 2013-07-17T12:01:58.197 回答
4

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

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);
    }
}
于 2015-01-11T09:37:49.837 回答
3

最后,我通过这种方式实现了这一点:

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

所以,每当我的单元测试被调用(比如从路径'A'),我的应用程序不会抱怨那个位置没有配置文件,因为我把我的配置文件放在路径'A'中。

(ps:我之所以得到汇编位置,是为了能够在那个位置找到我的配置文件)

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

于 2013-08-06T09:21:46.520 回答