Moq:单元测试IAuthorisationLoader(GetUsers()方法)

时间:2014-10-31 11:00:10

标签: c# asp.net-mvc unit-testing testing moq

我变得有点难过了。我的单元测试我的ServicesController,我调用不同的方法,如:

  • GetRoles()
  • GetDomains()
  • GetUsers()

在我的单元测试中,我已经检查了正在进行的呼叫并且正在正常运行,这一切都很好。但是我想创建一个Assert / call,我可以检查这个方法是否从我的模拟_userList返回X用户数量,并启用它们。

以下代码是我的GetUsers()方法:

    [CustomAuthorize]
    public ActionResult GetUsers(bool enabledOnly = true)
    {
        return new JsonNetResult { Data = _authorizationLoader.GetUsers(enabledOnly) };
    }

我想知道如何让我从我的_userList返回已启用的用户,并且能够在测试结束时调用正确的数量。

我的代码的这部分是该方法的单元测试:

    private User _user1;
    private User _user2;
    private User _user3;
    private User _user4;
    private User _user5;
    private bool isEnabled;
    private List<User> _userList;
    private Mock<IAuthorizationLoader> iAuthLoaderMock;

    public override void SetUp()
    {
        _user1 = new User
        {
            stuff needed is here
        };

        _user2 = new User
        {
            stuff needed is here
        };

        _user3 = new User
        {
            stuff needed is here
        };

        _user4 = new User
        {
            stuff needed is here
        };

        _user5 = new User
        {
           stuff needed is here
        };
        _userList = new List<User>();
        _userList.Add(_user1);
        _userList.Add(_user2);
        _userList.Add(_user3);
        _userList.Add(_user4);
        _userList.Add(_user5);
        isEnabled = true;
    }

    public override void Initialize()
    {
        iAuthLoaderMock = MockContainer.GetMock<IAuthorizationLoader>();
        iAuthLoaderMock.Setup(i => i.GetUsers(isEnabled)).Verifiable();
        base.Initialize(); // dont worry about this call it is needed though
    }

    public override void Because()
    {
        TestSubject.GetUsers(true);
      // this subject is created in code above but is unecessary to include
    }

    [TestMethod]
    public void The_controller_returns_only_enabled_users()
    {
        iAuthLoaderMock.Verify(i => i.GetUsers(isEnabled));

//---------------- Need to find a way of returning and checking this -------------------------//
                   //Assert.AreEqual(X (number of enabled users), new _userList.result(my result from test));
        }

任何帮助都会很棒,因为这让我很难过。感谢。

0 个答案:

没有答案