[英]Unable to perform mocking setup
I am trying to make use of nunit together with to do unit testing. 我正在尝试结合使用nunit和进行单元测试。 However I am experiencing this error: 但是我遇到此错误:
Moq.MockException: The following setups were not matched:
User m => m.encrptPassword(It.IsAny<String>(), It.IsAny<String>())
Moq.MockException:以下设置不匹配: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;
}
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. 如果您需要根据其他组件的输出来验证逻辑,则需要模拟。 Eg you have 例如,你有
public interface IEncrypter
{
string encryptPassword(string userID, string password);
}
and inject it to User class: 并将其注入User类:
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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.