单元测试 ASP.NET MVC5 应用程序 [英] Unit Testing ASP.NET MVC5 App

查看:24
本文介绍了单元测试 ASP.NET MVC5 应用程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过添加一个新属性来扩展 ApplicationUser 类(如教程中所示使用 Facebook 和 Google OAuth2 以及 OpenID 登录 (C#) 来创建 ASP.NET MVC 5 应用程序)

I'm extending the ApplicationUser class by adding a new property (as shown in the tutorial Create an ASP.NET MVC 5 App with Facebook and Google OAuth2 and OpenID Sign-on (C#))

public class ApplicationUser : IdentityUser
{
    public DateTime BirthDate { get; set; }
}

现在我想创建一个单元测试来验证我的 AccountController 是否正确保存了出生日期.

Now I want to create a Unit Test to verify that my AccountController is correctly saving the BirthDate.

我创建了一个名为 TestUserStore 的内存用户存储

I've created an in-memory user store named TestUserStore

[TestMethod]
public void Register()
{
    // Arrange
    var userManager = new UserManager<ApplicationUser>(new TestUserStore<ApplicationUser>());
    var controller = new AccountController(userManager);

    // This will setup a fake HttpContext using Moq
    controller.SetFakeControllerContext();

    // Act
    var result =
        controller.Register(new RegisterViewModel
        {
            BirthDate = TestBirthDate,
            UserName = TestUser,
            Password = TestUserPassword,
            ConfirmPassword = TestUserPassword
        }).Result;

    // Assert
    Assert.IsNotNull(result);

    var addedUser = userManager.FindByName(TestUser);
    Assert.IsNotNull(addedUser);
    Assert.AreEqual(TestBirthDate, addedUser.BirthDate);
}

controller.Register 方法是由 MVC5 生成的样板代码,但为了参考目的,我将其包含在此处.

The controller.Register method is boilerplate code generated by MVC5 but for reference purposes I'm including it here.

// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
    if (ModelState.IsValid)
    {
        var user = new ApplicationUser() { UserName = model.UserName, BirthDate = model.BirthDate };
        var result = await UserManager.CreateAsync(user, model.Password);
        if (result.Succeeded)
        {
            await SignInAsync(user, isPersistent: false);
            return RedirectToAction("Index", "Home");
        }
        else
        {
            AddErrors(result);
        }
    }

    // If we got this far, something failed, redisplay form
    return View(model);
}

当我调用Register时,它会调用SignInAsync,这就是问题所在.

When I call Register, it calls SignInAsync which is where the trouble will occur.

private async Task SignInAsync(ApplicationUser user, bool isPersistent)
{
    AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
    var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
    AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
}

在最底层,样板代码包含这个花絮

At the lowest layer, the boilerplate code includes this tidbit

private IAuthenticationManager AuthenticationManager
{
    get
    {
        return HttpContext.GetOwinContext().Authentication;
    }
}

这就是问题的根源所在.对 GetOwinContext 的调用是一种扩展方法,我无法模拟它,也无法用存根替换它(当然,除非我更改样板代码).

This is where the root of the problm occurs. This call to GetOwinContext is an extension method which I cannot mock and I cannot replace with a stub (unless of course I change the boilerplate code).

运行此测试时出现异常

Test method MVCLabMigration.Tests.Controllers.AccountControllerTest.Register threw exception: 
System.AggregateException: One or more errors occurred. ---> System.NullReferenceException: Object reference not set to an instance of an object.
at System.Web.HttpContextBaseExtensions.GetOwinEnvironment(HttpContextBase context)
at System.Web.HttpContextBaseExtensions.GetOwinContext(HttpContextBase context)
at MVCLabMigration.Controllers.AccountController.get_AuthenticationManager() in AccountController.cs: line 330
at MVCLabMigration.Controllers.AccountController.<SignInAsync>d__40.MoveNext() in AccountController.cs: line 336

在之前的版本中,ASP.NET MVC 团队非常努力地使代码可测试.从表面上看,现在测试 AccountController 并不容易.我有一些选择.

In prior releases the ASP.NET MVC team worked very hard to make the code testable. It seems on the surface that now testing an AccountController is not going to be easy. I have some choices.

我可以

  1. 修改样板代码,使其不调用扩展方法并在该级别处理此问题

  1. Modify the boiler plate code so that it doesn't call an extension method and deal with this problem at that level

设置 OWin 管道以进行测试

Setup the OWin pipeline for testing purposes

避免编写需要 AuthN/AuthZ 基础架构的测试代码(不是一个合理的选择)

Avoid writing testing code that requires the AuthN / AuthZ infrastructure (not a reasonable option)

我不确定哪条路更好.任何一个都可以解决这个问题.我的问题归结为哪种策略是最佳策略.

I'm not sure which road is better. Either one could solve this. My question boils down to which is the best strategy.

注意:是的,我知道我不需要测试不是我写的代码.MVC5 提供的 UserManager 基础结构就是这样一个基础结构,但是如果我想编写测试来验证我对 ApplicationUser 的修改或验证依赖于用户角色的行为的代码,那么我必须使用 UserManager 进行测试.

Note: Yes, I know that I don't need to test code that I didn't write. The UserManager infrastructure provided MVC5 is such a piece of infrastructure BUT if I want to write tests that verify my modifications to ApplicationUser or code that verifies behavior that depends upon user roles then I must test using UserManager.

推荐答案

我正在回答我自己的问题,所以如果您认为这是一个很好的答案,我可以从社区中了解一下.

I'm answering my own question so I can get a sense from the community if you think this is a good answer.

步骤 1:修改生成的 AccountController 以使用支持字段为 AuthenticationManager 提供属性设置器.

Step 1: Modify the generated AccountController to provide a property setter for the AuthenticationManager using a backing field.

// Add this private variable
private IAuthenticationManager _authnManager;

// Modified this from private to public and add the setter
public IAuthenticationManager AuthenticationManager
{
    get
    {
        if (_authnManager == null)
            _authnManager = HttpContext.GetOwinContext().Authentication;
        return _authnManager;
    }
    set { _authnManager = value; }
}

第 2 步:修改单元测试为Microsoft.OWin.IAuthenticationManager接口添加一个mock

Step 2: Modify the unit test to add a mock for the Microsoft.OWin.IAuthenticationManager interface

[TestMethod]
public void Register()
{
    // Arrange
    var userManager = new UserManager<ApplicationUser>(new TestUserStore<ApplicationUser>());
    var controller = new AccountController(userManager);
    controller.SetFakeControllerContext();

    // Modify the test to setup a mock IAuthenticationManager
    var mockAuthenticationManager = new Mock<IAuthenticationManager>();
    mockAuthenticationManager.Setup(am => am.SignOut());
    mockAuthenticationManager.Setup(am => am.SignIn());

    // Add it to the controller - this is why you have to make a public setter
    controller.AuthenticationManager = mockAuthenticationManager.Object;

    // Act
    var result =
        controller.Register(new RegisterViewModel
        {
            BirthDate = TestBirthDate,
            UserName = TestUser,
            Password = TestUserPassword,
            ConfirmPassword = TestUserPassword
        }).Result;

    // Assert
    Assert.IsNotNull(result);

    var addedUser = userManager.FindByName(TestUser);
    Assert.IsNotNull(addedUser);
    Assert.AreEqual(TestBirthDate, addedUser.BirthDate);
}

现在测试通过了.

好主意?坏主意?

这篇关于单元测试 ASP.NET MVC5 应用程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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