我正在编写测试,因为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);
}