如何模拟要测试的类的基类方法?

时间:2019-03-14 17:39:32

标签: c# unit-testing asp.net-core moq razor-pages

我正在尝试模拟一个类,该类用于将用户注册到系统(Asp.Net核心身份),当我逐步通过测试代码时,我可以看到它显然在注释失败在下面的 RegisterModel 中删除代码。 RegisterModelTests中注释掉的代码是我从在线挖掘尝试过的代码,但仍然无法使用。任何帮助深表感谢!

RegisterModel

public class RegisterModel : PageModel
{
    private readonly UserManager<IdentityUser> _userManager;

    public RegisterModel(
        UserManager<IdentityUser> userManager)
    {
        _userManager = userManager;
    }

    public async Task<IActionResult> OnPostAsync(
        string returnUrl = null)
    {
        returnUrl = returnUrl ?? Url.Content("~/");
        if (ModelState.IsValid)
        {
            var user = new IdentityUser { UserName = "test", Email = "test" };
            var result = await _userManager.CreateAsync(user, "test");

            if (result.Succeeded)
            {
                var code = await _userManager.GenerateEmailConfirmationTokenAsync(user);
                /*var callbackUrl = Url.Page(
                    "/Account/ConfirmEmail",
                    pageHandler: null,
                    values: new { userId = 23, code = code },
                    protocol: Request.Scheme);
                LocalRedirect(returnUrl);*/
            }
        }
        return Page();
    }
}

RegisterModelTests

[TestFixture]
public class RegisterModelTests
{
    private Mock<FakeUserManager> _mockUserManager;

    [SetUp]
    public void SetUp()
    {
        _mockUserManager = new Mock<FakeUserManager>();
        SetUpFakeUserManager();
    }

    public RegisterModel CreateRegisterModel()
    {
        return new RegisterModel(
            _mockUserManager.Object,
        );
    }

    [Test]
    public async Task GivenValidInput_OnPostAsync_CreatesANewUser()
    {
        // Arrange
        //var mockRegisterModel = new Mock<RegisterModel>() {CallBase = true};
        // mockRegisterModel.Setup(x => x.Url.Page(It.IsAny<string>(), It.IsAny<string>(), It.IsAny<IdentityUser>(),
        //        It.IsAny<string>())).Returns("Completed");
        var unitUnderTest = CreateRegisterModel();

        // Act
        //var result = await mockRegisterModel.Object.OnPostAsync("/asdsad/asda");
        var result = await unitUnderTest.OnPostAsync("/asdsad/asda");

        // Assert
        if (result != null)
            Assert.Pass();
    }

    private void SetUpFakeUserManager()
    {
        _mockUserManager.Setup(x => x.CreateAsync(It.IsAny<IdentityUser>(), It.IsAny<string>()))
            .ReturnsAsync(IdentityResult.Success);
    }

0 个答案:

没有答案