I want to check if the users password has been changed, what is the best way to write this test? Is my code in need of refactoring because it is wrong?
Inside the code password.ResetUserPassword – I find out which user is requesting a password change, if they can change, and generating an email if needs to be… Do I need to pass in a User objects to this method? This logic is called by my controller (or backend if needs to be)
[Test]
public void Test_If_New_Password_Is_Generated_For_User()
{
var repo = new ReadOnlySession();
var update = new UpdateSession();
var passwordService = new UserPasswordService();
var password = new AccountProfileProcessor(repo, update, passwordService);
password.ResetUserPassword("companyid", "jon.smithers", null);
Assert.Pass();
}
//The method that I am calling
_passwordService is a service that handles generating a new key for the user
public void ResetUserPassword(string identifier, string loginid, string passwordreseturl)
{
//get user object
var currentUser = _readOnlySession.All<User>()
.Where(x => x.Login == loginid)
.SingleOrDefault(); //any other logic to get user resides here...
if (currentUser == null)
throw new UserNotFoundException();
_passwordService.ResetPassword(currentUser.User, identifier, loginid);
//persist data
_updateSession.Update(currentUser.User);
//send out email with the url as a link inside the email
}
Something like the following would work. (I had to make a few assumptions about your classes, and I’m still not sure what type currentUser.User is.)
The trick with mocking and decoupling is to make all of your service dependencies interfaces.
You’ll need another interface dependency (with associated mock and verification) for the mail sending. You might want to put all of these in a separate test fixture, arrange in setup, then verify each service call in a separate test method.
To me this method is doing too much – it has multiple responsibilities. The painful test setup and multiple verifications are code smells. Consider breaking it into smaller methods (probably still called from the existing method) and then testing those independently.
GetUser(loginId)(or throw) would be the first method I’d extract. Moving some of these methods onto the services (such as the repository) would make this easier to test.Clarification – You mention in the comments that you want to check if the PasswordKey is different. That’s the responsibility of the concrete
UserPasswordService. You’ll need to test that independently.