我正在使用MSTest
和Moq
编写以下Razor Page处理程序方法的单元测试:
public async Task<IActionResult> OnPostAsync()
{
if (ModelState.IsValid)
{
var user = await _userManager.FindByEmailAsync(Input.Email);
if (user == null)
{
return Page();
}
// Trying to unit test this code here
if (!await _userManager.IsEmailConfirmedAsync(user))
{
return RedirectToPage("/Account/EmailNotConfirmed");
}
var code = await _userManager.GeneratePasswordResetTokenAsync(user);
code = WebEncoders.Base64UrlEncode(Encoding.UTF8.GetBytes(code));
var callbackUrl = Url.ResetPasswordCallbackLink(user.Id.ToString(), code, Request.Scheme);
var callbackLink = HtmlEncoder.Default.Encode(callbackUrl);
await _emailService.SendRazorTemplateEmailAsync(Input.Email, EmailTemplate.ResetPassword, new {Link = callbackUrl});
return RedirectToPage("/Account/ForgotPasswordSuccess", new { email = Input.Email });
}
return Page();
}
我正在尝试为其中await _userManager.IsEmailConfirmedAsync(user)
返回false
和RedirectToPage()
的代码块编写单元测试。这是我的单元测试代码:
private Mock<IEmailService> _emailService;
private Mock<ILogger<ForgotPasswordModel>> _logger;
private Mock<UserManager<ApplicationUser>> _userManager;
private Mock<IUserStore<ApplicationUser>> _userStore;
private ForgotPasswordModel _pageModel;
public ForgotPasswordTests()
{
_emailService = new Mock<IEmailService>();
_logger = new Mock<ILogger<ForgotPasswordModel>>();
_userStore = new Mock<IUserStore<ApplicationUser>>();
_userManager = new Mock<UserManager<ApplicationUser>>(_userStore.Object, null, null, null, null, null, null, null, null);
_pageModel = new ForgotPasswordModel(_emailService.Object, _logger.Object, _userManager.Object);
}
[TestMethod]
public async Task OnPostAsync_WhenUserHasNotConfirmedEmail_RedirectsToCorrectPage()
{
// Arrange
_pageModel.Input = new ForgotPasswordPageModel() { Email = "johndoe@email.com" };
_userManager.Setup(x => x.FindByEmailAsync(It.IsAny<string>())).ReturnsAsync(new ApplicationUser());
_userManager.Setup(x => x.IsEmailConfirmedAsync(It.IsAny<ApplicationUser>())).ReturnsAsync(false);
// Act
var result = await _pageModel.OnPostAsync();
// Assert
Assert.IsInstanceOfType(result, typeof(RedirectToPageResult));
Assert.AreEqual("/Account/EmailNotConfirmed", result.PageName); //<-- Error Here
}
我正在尝试编写一条Assert
语句来测试它是否重定向到正确的页面。当我调试单元测试时,我可以看到:
PageName = /Account/EmailNotConfirmed
,但是当我尝试以此做出Assert
语句时,出现以下错误:
'IActionResult' does not contain a definition for 'PageName' and no accessible extension method 'PageName' accepting a first argument of type 'IActionResult' could be found
我在做什么错了?
答案 0 :(得分:1)
您需要将结果转换为适当的类型,才能访问所需的成员
//...
// Act
IActionResult result = await _pageModel.OnPostAsync();
// Assert
Assert.IsInstanceOfType(result, typeof(RedirectToPageResult));
RedirectToPageResult redirect = result as RedirectToPageResult; //<--cast here
Assert.AreEqual("/Account/EmailNotConfirmed", redirect.PageName);