为什么我的扩展方法没有出现在我的测试班上? [英] Why is my Extension Method not showing up in my test class?

查看:45
本文介绍了为什么我的扩展方法没有出现在我的测试班上?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在System.Security.Principal.IIdentity上创建了一个名为HasContentPermission的扩展方法:

I created an extension method called HasContentPermission on the System.Security.Principal.IIdentity:

namespace System.Security.Principal
{
    public static class IdentityExtensions
    {
        public static bool HasContentPermission
            (this IIdentity identity, int contentID)
        {
            // I do stuff here
            return result;
        }
    }
}

我这样称呼它:

bool hasPermission = User.Identity.HasPermission(contentID);

像魅力一样工作.现在,我要对其进行单元测试.为此,我真正需要做的就是直接调用扩展方法,所以:

Works like a charm. Now I want to unit test it. To do that, all I really need to do is call the extension method directly, so:

using System.Security.Principal;

namespace MyUnitTests
{
    [TestMethod]
    public void HasContentPermission_PermissionRecordExists_ReturnsTrue()
    {
        IIdentity identity;
        bool result = identity.HasContentPermission(...

但是HasContentPermission不会智能.我尝试创建一个从IIdentity继承的存根类,但这也不起作用.为什么?

But HasContentPermission won't intellisense. I tried creating a stub class that inherits from IIdentity, but that didn't work either. Why?

还是我会以错误的方式进行操作?

Or am I going about this the wrong way?

推荐答案

请确保已:

  1. 将类设为静态
  2. 使该类可被调用代码访问
  3. 在要扩展的类型之前包括this
  4. 构建了包含扩展名的项目
  5. 在单元测试项目中添加了对该项目的引用
  6. 如果您的扩展方法包含在其他程序包中,则将using mypackage;添加到使用扩展方法的任何源文件中
  1. made the class static
  2. made the class accessible to the calling code
  3. included this before the type to extend
  4. built the project containing the extension
  5. added a reference to the project in your unit test project
  6. added a using mypackage; to any source file that uses the extension method if your extension method is contained inside a different package

请注意,您的示例中还存在(我认为是)错字,因为该方法不在类中.

Note that you've also got (I assume) a typo in your example in that the method isn't in a class.

最后,我将避免将方法放入官方.NET命名空间中.这只会让您之后的任何人感到困惑,他们可能认为该方法是官方支持的方法,而实际上它是您自己的并且包含在您的项目中.

Finally, I would avoid putting methods into the official .NET namespaces. It can only be confusing to anyone coming after you who might think that the method is an officially supported method when in reality it is your own and contained within your project.

这篇关于为什么我的扩展方法没有出现在我的测试班上?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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