Reputation: 25
I am trying to make use of nunit together with to do unit testing. However I am experiencing this error:
Moq.MockException: The following setups were not matched:
User m => m.encrptPassword(It.IsAny<String>(), It.IsAny<String>())
The following is the snippet of my code that is having issues:
private User _User;
Mock<User> mockUser;
[SetUp]
public void init()
{
mockUser = new Mock<User>();
_User = new User();
}
[Test]
[TestCase("1","admin","??????_????k0O???qr#??%szq??` ?j???????D>?????????Lvz??BP")]
public void encryptPasswordTest(string userID, string password, string output)
{
mockUser.Setup(m => m.encryptPassword(It.IsAny<string>(), It.IsAny<string>())).Returns(() => output);
string result = _User.encryptPassword(userID, password);
Assert.That(result.Equals(output));
mockUser.VerifyAll();
}
The following is the method that I am trying to mock
public virtual string encryptPassword(string userID, string password) {
string hashed = "";
HashAlgorithm sha256 = new SHA256CryptoServiceProvider();
string salted = userID + password;
byte[] result = sha256.ComputeHash(Encoding.ASCII.GetBytes(salted));
hashed = Encoding.ASCII.GetString(result);
return hashed;
}
Upvotes: 1
Views: 87
Reputation: 9175
You don't need any mocking in your case, you just have to check functions output:
[Test]
[TestCase("1","admin","??????_????k0O???qr#??%szq??` ?j???????D>?????????Lvz??BP")]
public void encryptPasswordTest(string userID, string password, string output)
{
string result = _User.encryptPassword(userID, password);
Assert.That(result.Equals(output));
}
You would need mocking if you'd need to validate your logic depending on output of another component. E.g. you have
public interface IEncrypter
{
string encryptPassword(string userID, string password);
}
and inject it to User class:
public User(IEncrypter encrypter) { this.encrypter = encrypter; }
Then you would mock it:
var mock = new Mock<IEncrypter>();
mock.Setup(m => m.encryptPassword(It.IsAny<string>(), It.IsAny<string>())).Returns(() => output);
var user = new User(mock.Object);
Upvotes: 2