如何使用System.Reflection.Assembly.GetEntryAssembly().Location执行单元测试 [英] How do I do Unit Testing with System.Reflection.Assembly.GetEntryAssembly().Location

查看:44
本文介绍了如何使用System.Reflection.Assembly.GetEntryAssembly().Location执行单元测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对单元测试有点陌生,我的大多数测试都相当容易做,并且表现出色.但是,我正在尝试测试此简单功能,但由于以下错误而使我失败:

I''m a bit new to unit testing, most of my tests are fairly easy to do and just works brilliantly. However I''m trying to test this simple function and it fails me with the following error:

System.NullReferenceException: Object reference not set to an instance of an object.


我究竟做错了什么? VS2010SP1
解决方案:由于下面的解决方案,我意识到了自己的错误,并改变了这一行,现在一切都是幸福.


What am I doing wrong? VS2010SP1
SOLUTION: Thanks to the solution below I realized my mistakes and changed one line to this and now all is bliss.

var s = Path.GetDirectoryName(new Uri(System.Reflection.Assembly.GetExecutingAssembly().Location).LocalPath)




类FolderSettings中的静态方法




Static method in class FolderSettings

public static String ProgramFolder
{
    get {
        var s = (Path.GetDirectoryName(System.Reflection.Assembly.GetEntryAssembly().Location));
        return s;
    }
}



TestMethod:



TestMethod:

/// <summary>
///A test for ProgramFolder
///</summary>
[TestMethod()]
public void ProgramFolderTest()
{
    string actual;
    actual = FolderSettings.ProgramFolder;
    Assert.Inconclusive("Verify the correctness of this test method.");
}

推荐答案

在运行单元测试时,输入程序集将成为测试托管外壳.这可能像nunit.exe程序集那样毫无用处,或者如果您使用的是二进制测试工具(例如Visual Studio本身),它将为null. (请参阅 GetEntryAssembly的文档 [
When you''re running the unit tests, the entry assembly will be the test hosting shell. That could be something useless like the nunit.exe assembly, or if you''re using a binary test harness (e.g. Visual Studio itself), it will be null. (See the documentation for GetEntryAssembly[^].)

You should either use GetExecutingAssembly, if that''s what you actually want to know in the general case (i.e. if someone links to your assembly, do you want the location of your assembly still?), or accept that something like this which is making assumptions about environment (i.e. that a particular assembly will be the primary entry point) is intrinsically not unit testable and not worry about it.

Considering it''s a one line call to an external dependency (the Framework) which you can assume is well tested, I don''t think you need a (pseudo-)unit test for this property anyway.


这篇关于如何使用System.Reflection.Assembly.GetEntryAssembly().Location执行单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆