I'm trying to Unit test my login method, for that I used below provider

var provider = Substitute.For<Sitecore.Security.Authentication.AuthenticationProvider>();
                .Login("extranet\[email protected]", "Test@123", false)

and used this in using block.

using(var db = new Sitecore.FakeDb.Db("master"){ new Sitecore.FakeDb.DbItem("home")} )
            using (new Sitecore.Security.Authentication.AuthenticationSwitcher(provider))
                var item = db.GetItem("/sitecore/content/home"); //Here the error throws "User cannot be null"

                var loginResult = Sitecore.Security.Authentication.AuthenticationManager.Login("extranet\[email protected]", "Test@123");

I'm able to test the sitecore Login method but inside that block the I'm not able to do any activity like DataBase.GetItem() or AuthenticationManager.GetActiveUser() which throws an error saying System.InvalidOperationException: 'User cannot be null.'

1 Answer 1


For testing authentication using FakeDb you can try next :

    public void Login_UserIsNotLoggedIn_ShouldReturnFalse(FakeMembershipUser user, AuthenticationProvider authenticationProvider, AccountRepository repo)
        authenticationProvider.Login(@"somedomain\John", Arg.Any<string>(), Arg.Any<bool>()).Returns(false);

        var context = new FakeSiteContext(new StringDictionary
                                              {"domain", "somedomain"}
        using (new Switcher<Domain, Domain>(new Domain("somedomain")))
            using (new AuthenticationSwitcher(authenticationProvider))
                var loginResult = repo.Login("John", "somepassword");

More tests you can find at : https://github.com/Sitecore/Habitat/blob/master/src/Feature/Accounts/Tests/AccountsRepositoryTests.cs

  • My issue is- inside that using block with AuthenticationSwitcher, I cannot get Sitecore.Security.Accounts.User.Current (throws that error), outside the current user is default\anonymous
    – Jojo
    Jul 10, 2018 at 8:14
  • why do you want to use Current User? and why you don't hardcode with user name and password? Jul 10, 2018 at 8:16
  • In the method which I'm testing, there are sitecore APIs(Database.GetItem()) used after the login code. Where it fails by throwing that error, There is no issue in testing Login, but since the code we have other code also UT is failing for the method. And this happens inside that using block.
    – Jojo
    Jul 10, 2018 at 8:38
  • For the current user it is obvious that you are not able to get it, because you are located outside of the request. What I suggest is that you just mock the method and that's it Jul 10, 2018 at 9:59

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.