Mocking new Microsoft Entity Framework Identity UserManager and RoleManager

后端 未结 6 502
我寻月下人不归
我寻月下人不归 2020-12-08 13:46

Has anyone come up with a successful mocking solution for UserManager and RoleManager? I have been beating my head against a wall all day. All I wa

6条回答
  •  一向
    一向 (楼主)
    2020-12-08 14:08

    You won't be able to Mock UserManager or RoleManager directly. What you CAN do, however, is mock an object that uses them.

    For Example:

    public interface IWrapUserManager
    {
        UserManager WrappedUserManager {get; set;}
        //provide methods / properties that wrap up all UserManager methods / props.
    }
    
    public class WrapUserManager : IWrapUserManager
    {
        UserManager WrappedUserManager {get; set;}
        //implementation here. to test UserManager, just wrap all methods / props.
    }
    
    //Here's a class that's actually going to use it.
    public class ClassToTest
    {
        private IWrapUserManager _manager;
        public ClassToTest(IWrapUserManager manager)
        {
            _manager = manager;
        }
        //more implementation here
    }
    

    On to the mocking:

    [TestClass]
    public class TestMock
    {
        [TestMethod]
        public void TestMockingUserManager()
        {
            var mock = new Mock();
            //setup your mock with methods and return stuff here.
            var testClass = new ClassToTest(mock.Object); //you are now mocking your class that wraps up UserManager.
            //test your class with a mocked out UserManager here.
        }
    }
    

提交回复
热议问题