【发布时间】:2016-09-26 05:14:13
【问题描述】:
我正在为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);
}
【问题讨论】:
-
您发布的代码看起来不像真正的单元测试——它从不调用任何东西,除了模拟。请验证您的单元测试代码并显示您正在尝试测试的实现。
-
它在 bool passWordMatch = userMangerMock.CheckPassword(userInfo.Id, userInfo.Password);我已经更新了 CheckPassword() 实现。
-
userManagerMock.CheckPassword() 正在调用模拟对象上的方法。那时你没有调用任何真正的代码。
标签: c# rhino-mocks rhino-mocks-3.5