看起来你还没有将依赖关系从中分离出来 AdminController 构造函数。
AdminController
您需要传递抽象/接口,而不是传递实现:
public AdminController(IHostingEnvironment environment, ISignInManager<IdentityUser> signInManager, ILogger<LoginModel> logger, IRoleManager<IdentityRole> roleManager, IUserManager<IdentityUser> userManager)
请注意,我只添加了 I 前缀,但它意味着需要重构您的代码以传递接口,如我所提到的。
I
现在,我们可以嘲笑 AdminController 容易:
[TestFixure] public class AdminControllerTests { private AdminController _adminController; private IHostingEnvironment _hostingEnvironment = new Mock<IHostingEnvironment>(); private ISignInManager<IdentityUser> _signInManager = new Mock<ISignInManager<IdentityUser>>();
该 _signInManager 将需要一个使用返回ISignInManager的方法的设置 ISignInManager ,让我们假设它的名字 Builder() 。 *注意还有其他的嘲笑方法,这里有 二 方式,或考虑使用 autofac
_signInManager
ISignInManager
Builder()
[SetUp] public void SetUp() { _signInManager.Setup(a => a.Builder()).Returns(new[] { new IdentityUser() }); //Do the same for the rest of the dependencies. //... _adminController = new AdminController(_hostingEnvironment, _signInManager.Object, ...); }
现在你可以利用了 _adminController 实例(请参阅正确的命名 惯例 对于测试方法):
_adminController
[Test] public void Verify_AdminController_Is_Decorated_With_Authorize_Attribute() { //... var actionResult = _adminController.AddUserToRole(user, userRole).Result; //... } }