我正在为CheckPassWord()
编写测试
我认为Expect调用在我的userMangerMock上没有按预期运行。
//CheckPassword returns true if the parameter matches to the exsting user.
//Existing user is obtained by GetUser() by internal call
bool passWordMatch = userMangerMock.CheckPassword(userInfo.Id, userInfo.Password);
CheckPassWord()在内部调用GetUser(),
由于GetUser()需要更深入的内部调用,我决定返回stubUser
我相信Expect()的实现就足够了。
请注意,以下调用var userInfo = userMangerMock.GetUser("TestManager");
正在返回stubUser
。
但是,CheckPassword()
调用我假设stubUser
未返回,因此测试失败。
如果以下UT中有任何错误,请纠正我。
//Use TestInitialize to run code before running each test
[TestInitialize()]
public void MyTestInitialize()
{
CreateUser();
}
private static IUser _stubUser;
public void CreateUser()
{
IUserFactory iUserFactory = new UserFactory();
UserParams parameters = new UserParams();
parameters.Password = "TestPassword123!";
parameters.UserID = "TestManager";
_stubUser = iUserFactory.CreateUser(parameters);
}
/// <summary>
///A test for CheckPassword
///</summary>
[TestMethod( )]
public void CheckPasswordTest()
{
// !!! Below I've used WhenCalled() to show you that correct
// expectation is called based on argument type, just see in debugger
IUserManager userMangerMock = MockRepository.GenerateMock<IUserManager>();
userMangerMock.Expect(x => x.GetUser(Arg<string>.Is.Anything))
.WhenCalled((mi) =>
{
Debug.WriteLine("IUserManager - string parameter");
})
.Return(_stubUser);
var userInfo = userMangerMock.GetUser("TestManager");
bool passWordMatch = userMangerMock.CheckPassword(userInfo.Id, userInfo.Password);
userMangerMock.VerifyAllExpectations();
Assert.AreEqual(true, passWordMatch);
}
/// <summary>
/// Returns true if password matches the user
/// </summary>
public bool CheckPassword(string userId, string password)
{
if (userId == null)
{
throw new ArgumentNullException("userId");
}
IUser user = GetUser(userId);
if (user == null)
{
throw new UserManagementException(UserManagementError.InvalidUserId);
}
return (user.Password == password);
}
答案 0 :(得分:1)
我在测试中注意到的一些事情:
userMangerMock.VerifyAllExpectations();
这将永远通过,因为您在测试代码本身中手动调用GetUser():
var userInfo = userMangerMock.GetUser("TestManager");
因此,您实际上可以删除此验证通话,因为它不需要。
感觉您的单元测试似乎没有为您提供任何价值,因为它在硬编码的模拟对象上断言。
var userInfo = userMangerMock.GetUser("TestManager");
bool passWordMatch = userMangerMock.ChePassword(userInfo.Id, userInfo.Password);
Assert.AreEqual(true, passWordMatch);
如果userInfo
是对存根对象_stubUser
的引用,那么您的单元测试可以重构为:
bool passWordMatch = userMangerMock.CheckPassword(_stubUser.Id, _stubUser.Password);
Assert.AreEqual(true, passWordMatch);