我遇到了单元测试的一些问题.
DefaultHttpContext.RequestServices是nullAuthenticationService对象,但我不知道要传递什么参数我该怎么办?如何进行单元测试HttpContext.SignInAsync()?
正在测试的方法
public async Task<IActionResult> Login(LoginViewModel vm, [FromQuery]string returnUrl)
{
if (ModelState.IsValid)
{
var user = await context.Users.FirstOrDefaultAsync(u => u.UserName == vm.UserName && u.Password == vm.Password);
if (user != null)
{
var claims = new List<Claim>
{
new Claim(ClaimTypes.Name, user.UserName)
};
var identity = new ClaimsIdentity(claims, "HappyDog");
// here
await HttpContext.SignInAsync(new ClaimsPrincipal(identity));
return Redirect(returnUrl ?? Url.Action("Index", "Goods"));
}
}
return View(vm);
}
Run Code Online (Sandbox Code Playgroud)
到目前为止我尝试过的.
[TestMethod]
public async Task LoginTest()
{
using …Run Code Online (Sandbox Code Playgroud) 我正在尝试测试此控制器方法,以确保它重定向到另一个控制器方法或存在模型错误。
public IActionResult ResetPassword(ResetPasswordViewModel viewModel)
{
if (viewModel.NewPassword.Equals(viewModel.NewPasswordConfirm))
{
...do stuff
return RedirectToAction("Index", "Home");
}
ModelState.AddModelError("ResetError", "Your passwords did not match. Please try again");
return View(viewModel);
}
Run Code Online (Sandbox Code Playgroud)
当我运行测试时,我收到两条不同的错误消息。当它尝试 RedirectToAction 时,我收到错误...
System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Mvc.Routing.IUrlHelperFactory' has been registered.
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService(IServiceProvider provider, Type serviceType)
at Microsoft.Extensions.DependencyInjection.ServiceProviderServiceExtensions.GetRequiredService[T](IServiceProvider provider)
at Microsoft.AspNetCore.Mvc.ControllerBase.get_Url()
at Microsoft.AspNetCore.Mvc.ControllerBase.RedirectToAction(String actionName, String controllerName, Object routeValues, String fragment)
at Microsoft.AspNetCore.Mvc.ControllerBase.RedirectToAction(String actionName, String controllerName, Object routeValues)
at Microsoft.AspNetCore.Mvc.ControllerBase.RedirectToAction(String actionName, String controllerName)
Run Code Online (Sandbox Code Playgroud)
当它尝试返回视图时,错误消息是...
System.InvalidOperationException : No service for type 'Microsoft.AspNetCore.Mvc.ViewFeatures.ITempDataDictionaryFactory' has …Run Code Online (Sandbox Code Playgroud)