模拟管理员控制器进行单元测试

时间:2018-06-16 16:48:59

标签: c# unit-testing moq xunit

我正在使用ASP.NET Core 2.0,使用xUnit和Moq为管理功能创建单元测试。我有一个AdminController.cs,它在其构造函数

中使用依赖注入
private UserManager<AppUser> userManager;
private IUserValidator<AppUser> userValidator;
private IPasswordValidator<AppUser> passwordValidator;
private IPasswordHasher<AppUser> passwordHasher;
private RoleManager<IdentityRole> roleManager;
private SignInManager<AppUser> signInManager;

我尝试在单元测试中以下列方式安排它们

// Arrange
Mock<EFRepository> mockRepo = new Mock<EFRepository>();
var userStoreMock = new Mock<IUserRoleStore<AppUser>>();
var userManager = new UserManager<AppUser>(userStoreMock.Object, null, null, null, null, null, null, null, null);
AppUser user = new AppUser();

var roleStoreMock = new Mock<IRoleStore<IdentityRole>>();
var userValidator = new Mock<IUserValidator<AppUser>>();
var passwordValidator = new Mock<IPasswordValidator<AppUser>>();
var passwordHasher = new Mock<IPasswordHasher<AppUser>>();
var roleManager = new RoleManager<IdentityRole>(roleStoreMock.Object, null, null, null, null, null);
var signInManager = new Mock<SignInManager<AppUser>>();

//THIS LINE CAUSES THE ERROR
AdminController controller = new AdminController(userManager, userValidator.Object, passwordValidator.Object, passwordHasher.Object, roleManager, signInManager.Object);

我收到以下错误:

Can not instantiate proxy of class: Microsoft.AspNetCore.Identity.SignInManager Could not find a parameterless constructor.

我还没有找到一种正确的方法来模仿有效的SignInManager

我一直试图使用下面的方法而没有成功:

private Mock<SignInManager<AppUser>> GetMockSignInManager()
{
    var mockUsrMgr = GetMockUserManager();
    var mockAuthMgr = new Mock<AuthenticationManager>();
    var mockContextAssosor = new Mock<IHttpContextAccessor>();
    var mockClaimsFactory = new Mock<IUserClaimsPrincipalFactory<AppUser>>();
    //i am unclear on how to mock the options
    var opts = new Mock<IOptions<>>();
    var mockLogger = new Mock<ILogger<SignInManager<AppUser>>>();
    //namespace for IAuthenicationSchemeProvider is not recognized
    var scheme = new Mock<IAuthenticationSchemeProvider>();
    //return new Mock<SignInManager<AppUser>>(mockUsrMgr.Object, mockAuthMgr.Object...and so on);
}

1 个答案:

答案 0 :(得分:1)

private Mock<SignInManager<AppUser>> GetMockSignInManager()
{
    var mockUsrMgr = new UserManager<AppUser>(userStoreMock.Object, null, null, null, null, null, null, null, null);
    var ctxAccessor = new HttpContextAccessor();
    var mockClaimsPrinFact = new Mock<IUserClaimsPrincipalFactory<AppUser>>();
    var mockOpts = new Mock<IOptions<IdentityOptions>>();
    var mockLogger = new Mock<ILogger<SignInManager<AppUser>>>();

    return new Mock<SignInManager<AppUser>>(mockUsrMgr.Object, ctxAccessor, mockClaimsPrinFact.Object, mockOpts.Object, mockLogger.Object);
}