Asp.net mvc 5 如何使用nsubstitute和nunit模拟ApplicationUserManager进行单元测试

Asp.net mvc 5 如何使用nsubstitute和nunit模拟ApplicationUserManager进行单元测试,asp.net-mvc-5,nunit,nsubstitute,Asp.net Mvc 5,Nunit,Nsubstitute,我在使用nsubstitute和nunit模拟ApplicationUserManager类以测试我的操作方法时遇到问题。这是我嘲笑全班同学的方式 var\u userManager=Substitute.For(); 在我的测试系统中,我使用构造函数注入来注入类。当我运行测试时,我得到这个错误消息 Castle.DynamicProxy.InvalidProxyConstructorArgumentsException:无法实例化类的代理:JobHub.Web.Identity.Applic

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

var\u userManager=Substitute.For();
在我的测试系统中,我使用构造函数注入来注入类。当我运行测试时,我得到这个错误消息

Castle.DynamicProxy.InvalidProxyConstructorArgumentsException:无法实例化类的代理:JobHub.Web.Identity.ApplicationUserManager。
找不到无参数构造函数。
我的问题是如何正确地使用NSubstitue模拟这个类,就像我使用类的
SetPhoneNumberAsync()
方法一样

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

[HttpPost]
[ValidateAntiForgeryToken]
公共异步任务创建(UserProfileView模型)
{
if(ModelState.IsValid)
{
var userId=User.Identity.GetUserId();
var profile=model.MapToProfile(userId);
if(CommonHelper.IsNumerics(model.PhoneNo))
{
wait_userManager.SetPhoneNumberAsync(userId,model.PhoneNo);
}
if(model.ProfileImage!=null)
{
profile.ProfileImageUrl=wait _imageService.SaveImage(model.ProfileImage);
}
_profileService.AddProfile(profile);
_unitofWork.SaveChanges();
//重定向到下一页(即:设置体验)
返回重定向到操作(“技能”、“设置”);
}
返回视图(“用户配置文件”,模型);
}
当未提供所需的构造函数参数时,会发生此错误。如果
MyClass
构造函数接受两个参数,则可以如下所示进行替换:

var sub = Substitute.For<MyClass>(firstArg, secondArg);
var sub=替换为(第一个参数,第二个参数);
请记住,NSubstitute不能与非虚拟方法一起工作,在替换类(而不是接口)时,有时可以执行真正的代码


这将在中进一步解释。

是的,但是如何创建一个不执行实际代码而只调用传递给它的回调的真实类的替代品呢。我尝试使用,虽然它调用回调,但它仍然调用真正的代码。如果不是,可以通过moq实现吗?构造函数代码和非虚拟成员中的代码将始终运行。我相信Moq、Fakeitesy和Rhinomock也有类似的限制,尽管值得检查这些项目和/或发布一个通用的.net模拟问题。确保真实代码不会运行的最佳方法是使用接口(因为它们没有真实代码)。如果您无法编辑原始类,一个选项是使用适配器模式使原始类符合接口。非常感谢,通过使用Moq扩展方法模拟
IUserStore
IUserPhoneNumberStore
并返回所需的
任务,我终于解决了问题,并通过了测试。虽然它看起来有点凌乱,但它可以工作。