Search code examples
c#.netnunitmoquserprincipal

MOQ return new object from method with parameters


Having a bit of trouble on this. I am attempting to use Moq for the first time.

I have an interface:

public interface IUserService
{
    void SignOut(string username);
    AuthenticationResult Authenticate(string username, string password);
    Models.Users.ApplicationUser GetAvailibleUserDetails(string username);
    List<ApplicationUser> GetAvailibleUsers();
    List<ApplicationUser> GetApplicationUsers();
    ApplicationUser GetUser(Expression<Func<ApplicationUser, bool>> filter);
    ApplicationUser AddUser(string username, List<string> environmentIds, bool isAdmin =false);
    ApplicationUser UpdateUser(string id, List<string> environmentIds, bool isAdmin = false);
    void DeleteUser(string id);
}

The Authenticate method using the using System.DirectoryServices.AccountManagement library for AD authentication.

Here is the implementation of the the method:

public AuthenticationResult Authenticate(string username, string password)
    {
        UserPrincipal userPrincipal = null;

        var isAuthenticated = _adManager.ValidateUser(username, password);

        if (isAuthenticated)
        {
            userPrincipal = _adManager.GetUserPrincipal(username);
        }


        if (!isAuthenticated || userPrincipal == null)
        {
            return new AuthenticationResult("Username or Password is not correct");
        }

        if (userPrincipal.IsAccountLockedOut())
        {
            // here can be a security related discussion weather it is worth 
            // revealing this information
            return new AuthenticationResult("Your account is locked.");
        }

        if (userPrincipal.Enabled.HasValue && userPrincipal.Enabled.Value == false)
        {
            // here can be a security related discussion weather it is worth 
            // revealing this information
            return new AuthenticationResult("Your account is disabled");
        }

        //Determine if the user is authorized to use the application
        var user = _userManager.GetUser(u => u.LdapId == userPrincipal.Sid.Value);
        if (user == null)
        {
            return new AuthenticationResult("You are not authorized to use this application");
        }

        var identity = CreateIdentity(userPrincipal, user);

        _authenticationManager.SignOut("MAG.EPM");
        _authenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = false }, identity);


        return new AuthenticationResult();
    }

Here is my test class and method:

public class UserServiceTest
{
    private readonly Mock<IActiveDirectoryManager> _adManager;
    private readonly Mock<UserPrincipalWrapper> _userPrincipal;
    private readonly Mock<IUserManager> _userManager;
    private readonly Mock<IAuthenticationManager> _authenticationManager;

    public UserServiceTest()
    {
        _userPrincipal = new Mock<UserPrincipalWrapper>();
        _userManager = new Mock<IUserManager>();
        _adManager = new Mock<IActiveDirectoryManager>();
        _authenticationManager = new Mock<IAuthenticationManager>();
    }

    [TestMethod]
    public void Authenticate_ValidActiveDirectoryUser_Authenticated()
    {
        _userPrincipal.Setup(x => x.IsAccountLockedOut()).Returns(false);
        _userPrincipal.SetupGet(x => x.Enabled).Returns(true);


        _adManager.Setup(x => x.ValidateUser("testUser", "password")).Returns(true);
        _adManager.Setup(x => x.GetUserPrincipal("testUser")).Returns(_userPrincipal.Object);

        _userManager.Setup(x => x.GetUser(u => u.LdapId == Guid.NewGuid().ToString())).Returns(new ApplicationUser());

        IUserService userService = new UserService(_userManager.Object, _authenticationManager.Object, _adManager.Object);


        Assert.IsTrue(userService.Authenticate("testUser", "password").IsSuccess);

    }

}

The problem is I am getting a null reference on the user object returned from the

//Determine if the user is authorized to use the application
        var user = _userManager.GetUser(u => u.LdapId == userPrincipal.Sid.Value);
        if (user == null)
        {
            return new AuthenticationResult("You are not authorized to use this application");
        }

Based on my setup - it should just return a new ApplicationUser()

Everything else is working fine.

The IUserManager interface looks like:

    public interface IUserManager
{
    List<ApplicationUser> GetUsers(Expression<Func<ApplicationUser, bool>> filter = null);
    ApplicationUser GetUser(Expression<Func<ApplicationUser, bool>> filter);
    ApplicationUser AddUser(string username, List<string> environmentIds, bool isAdmin = false);
    void DeleteUser(string username);
    ApplicationUser UpdateUser(string id, List<string> environmentIds, bool isAdmin = false);
    IList<string> GetUserRoles(string id);


}

So for the _userManager.Setup(u => u.LdapId == Guid.NewGuid().tostring())).Returns(new ApplicationUser());

I am trying to replace the _userManager.GetUser(u => u.LdapId == userPrincipal.Sid.Value);

I did try replacing the test method with

_userManager.Setup(x => x.GetUser(u => u.LdapId == _userPrincipal.Object.Sid.Value)).Returns(new ApplicationUser());

to match the call in the implementation, but I get a null reference exception ("Object not set...") on the _userPrincipal object.


Solution

  • Try it like this:

    userService
        .Setup(s => s.GetUser(It.IsAny<Expression<Func<ApplicationUser, bool>>>()))
        .Returns(new ApplicationUser());