我在 System.Security.Principal.IIdentity
上创建了一个名为 HasContentPermission
的扩展方法:
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);
像魅力一样工作。现在我想对其进行单元测试。为此,我真正需要做的就是直接调用扩展方法,因此:
using System.Security.Principal;
namespace MyUnitTests
{
[TestMethod]
public void HasContentPermission_PermissionRecordExists_ReturnsTrue()
{
IIdentity identity;
bool result = identity.HasContentPermission(...
但是 HasContentPermission
不会智能感知。我尝试创建一个继承自 IIdentity
的 stub 类,但这也不起作用。为什么?
还是我做错了?
最佳答案
确保您:
- 使类静态化
- 使调用代码可以访问该类
- 在要扩展的类型之前包含
this
- 构建包含扩展的项目
- 在您的单元测试项目中添加对项目的引用
- 添加
using mypackage;
到任何使用扩展方法的源文件,如果您的扩展方法包含在不同的包中
请注意,您的示例中也有(我假设)拼写错误,因为该方法不在类中。
最后,我会避免将方法放入官方 .NET 命名空间中。这只会让追随您的人感到困惑,他们可能认为该方法是官方支持的方法,而实际上它是您自己的并包含在您的项目中。
关于c# - 为什么我的扩展方法没有出现在我的测试类中?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2525205/