如何模拟应用程序用户管理器使用 nreplace 和 nunit 进行单元测试



我在使用 nsubstitute 和 nunit 模拟ApplicationUserManager类来测试我的操作方法时遇到问题。这是我嘲笑班级的方式。

var _userManager = Substitute.For<ApplicationUserManager>();

在我的测试系统中,我使用构造函数注入注入类。当我运行测试时,我收到此错误消息。

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException : Can not instantiate proxy of class: JobHub.Web.Identity.ApplicationUserManager.
Could not find a parameterless constructor.

我的问题是我如何使用 NSubstitue 正确模拟这个类,就像我使用该类的 SetPhoneNumberAsync() 方法一样。

编辑顺便说一下,这是我试图测试的代码段

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Create(UserProfileView model)
{
    if (ModelState.IsValid)
    {
        var userId = User.Identity.GetUserId(); 
        var profile = model.MapToProfile(userId);
        if (CommonHelper.IsNumerics(model.PhoneNo))
        {
            await _userManager.SetPhoneNumberAsync(userId, model.PhoneNo);
        }
        if (model.ProfileImage != null)
        {
            profile.ProfileImageUrl = await _imageService.SaveImage(model.ProfileImage);
        }
        _profileService.AddProfile(profile);
        _unitofWork.SaveChanges();
        //Redirect to the next page (i.e: setup experiences)
        return RedirectToAction("Skills", "Setup");
    }
    return View("UserProfile", model);
}
替换

具体类但尚未提供所需的构造函数参数时,会发生此错误。如果一个MyClass构造函数接受两个参数,则可以像这样替换它:

var sub = Substitute.For<MyClass>(firstArg, secondArg);

请记住,NSubstitute 不能使用非虚拟方法,并且在替换类(而不是接口)时,在某些情况下可以执行真实代码。

这在创建替代品中有进一步的解释。

最新更新