【问题标题】:Get Moq to call a base class method that has not been overriden获取 Moq 以调用尚未被覆盖的基类方法
【发布时间】:2016-07-09 14:52:28
【问题描述】:

我在我的 MVC 应用程序中使用 Asp.Net Identity,并且我有一个名为 ApplicationSignInManager 的类,如下所示:

public class ApplicationSignInManager : SignInManager<ApplicationUser, string>
{
    public ApplicationSignInManager(ApplicationUserManager userManager, 
        IAuthenticationManager authenticationManager)
        : base(userManager, authenticationManager)
    {
    }

    public override Task<ClaimsIdentity> CreateUserIdentityAsync(ApplicationUser user)
    {
        return user.GenerateUserIdentityAsync((ApplicationUserManager)UserManager);
    }

    public static ApplicationSignInManager Create(IdentityFactoryOptions<ApplicationSignInManager> options, 
        IOwinContext context)
    {
        return new ApplicationSignInManager(context.GetUserManager<ApplicationUserManager>(), 
            context.Authentication);
    }
}

现在,我想为控制器上的操作编写单元测试。我正在使用带有 Moq 4.5.10 的 Microsoft Visual Studio 单元测试框架。

该操作调用PasswordSignInAsync 方法,该方法在基类SignInManager&lt;ApplicationUser, string&gt; 中声明为virtual,但在子类ApplicationSignInManager 中未被覆盖。

我也试过这个选项:

var mockSignInManager = new Mock<ApplicationSignInManager>()
        { CallBase = true };

mockSignInManager.Setup(
      m => m.PasswordSignInAsync(string.Empty, string.Empty, true, true));

但是 PasswordSignInAsync 没有出现在 Intellisense 中,编译器抱怨它无法在 ApplicationSignInManager 上找到该方法。

如何让它显示出来?

【问题讨论】:

    标签: .net unit-testing tdd moq


    【解决方案1】:

    我在单元测试项目中安装了 NuGet 包 Microsoft.AspNet.Identity.Owin 并开始获取基类中的所有方法,因为该基类位于 Microsoft. AspNet.Identity.Owin.dll 程序集。

    简而言之,如果您想访问模拟对象中基类的方法,那么如果该基类位于与派生类不同的程序集中,则必须在测试项目中添加对基类程序集的引用.

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-03-03
      • 1970-01-01
      • 2010-10-18
      • 1970-01-01
      相关资源
      最近更新 更多