我正在寫測試CheckPassWord()
我假設在我的userMangerMock上,Expect調用的行爲與預期不符。預計通話不會在模擬
//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
我相信實現期望的()就足夠了點。 請注意,以下電話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);
}
代碼你張貼看起來並不像真正的單元測試 - 它永遠不會調用除了嘲笑之外的任請驗證您的單元測試代碼,並顯示您正在嘗試測試的實現。 –
它清楚地調用bool的CheckPassword passWordMatch = userMangerMock.CheckPassword(userInfo.Id,userInfo.Password);我更新了CheckPassword()實現。 – Srikanth
userManagerMock.CheckPassword()正在調用模擬對象上的方法。在這一點上你沒有調用任何真正的代碼。 – Pedro