2
如何在調用ForgotMyPassword(...)時測試「TestProperty」是否設置了值?Rhino Mocks示例如何模擬屬性
> public interface IUserRepository
{
User GetUserById(int n);
}
public interface INotificationSender
{
void Send(string name);
int TestProperty { get; set; }
}
public class User
{
public int Id { get; set; }
public string Name { get; set; }
}
public class LoginController
{
private readonly IUserRepository repository;
private readonly INotificationSender sender;
public LoginController(IUserRepository repository, INotificationSender sender)
{
this.repository = repository;
this.sender = sender;
}
public void ForgotMyPassword(int userId)
{
User user = repository.GetUserById(userId);
sender.Send("Changed password for " + user.Name);
sender.TestProperty = 1;
}
}
// Sample test to verify that send was called
[Test]
public void WhenUserForgetPasswordWillSendNotification_WithConstraints()
{
var userRepository = MockRepository.GenerateStub<IUserRepository>();
var notificationSender = MockRepository.GenerateStub<INotificationSender>();
userRepository.Stub(x => x.GetUserById(5)).Return(new User { Id = 5, Name = "ayende" });
new LoginController(userRepository, notificationSender).ForgotMyPassword(5);
notificationSender.AssertWasCalled(x => x.Send(null),
options => options.Constraints(Rhino.Mocks.Constraints.Text.StartsWith("Changed")));
}
對不起阿倫,之前我張貼了同樣的答案我沒有刷新。 +1 – Bermo 2010-04-10 12:50:11
>是否有方法來測試該方法被調用時的屬性設置?如果該物業設置多次?例如: public void ForgotMyPassword(int userId) { User user = repository.GetUserById(userId); sender.Send(「更改密碼爲」+ user.Name); sender.TestProperty = 1; 重置(); sender.TestProperty = 2; 重置(); sender.TestProperty = 3; } – guazz 2010-04-10 13:35:58
存根會自動獲取屬性行爲。我相信你可以檢查該屬性是否在模擬上設置了特定的值,但是你正在測試的方法調用者應該只關心TestProperty在方法返回時的值 - 我會將其視爲代碼異味。 – 2010-04-10 14:26:52