为什么这种期望失败了?

时间:2009-07-30 03:00:25

标签: c# unit-testing rhino-mocks

我正在设置一些RhinoMock测试,但我无法弄清楚为什么我的期望会失败。

以下是我正在测试的类/接口:

public class LogOn {
    public virtual ILogOn View { get; set; }
    public virtual IDataProvider DataProvider { get; set; }

    public void SetUp(ILogOn view) {
        this.View = view;
        this.DataProvider = ... //using dependancy injection to do the data provider, so I want it faked in tests
    }
    public void SetUpEvents() {

        this.View.Submit += new EventHandler(View_Submit);
    }

    void View_Submit(object sender, EventArgs e) {
        if ( this.DataProvider.LogOn(this.Username) ) {
            this.View.SubmitSuccess();
        } else {
            this.View.SubmitFailure("Username is incorrect");
        }
    }
}

public interface ILogOn {
    string Username { get; set; }
    event EventHandler Submit;
    void SubmitSuccess();
    void SubmitFailure(string message);
}

这是我的测试方法:

[TestMethod]
public void LogOnFailure() {
    var dataProvider = MockRepository.CreateStub<DataProvider>();
    var presenter = MockRepository.CreateMock<LogOn>();
    var view = MockRepository.CreateMock<ILogOn>();

    dataProvider.Expect(d => d.LogOn(null)).Return(true).Repeat.Any();

    presenter.Expect(p => p.DataProvider).Return(dataProvider).Repeat.Any();
    presenter.Expect(p => p.View).Return(view).Repeat.Any();
    presenter.Expect(p => p.SetUpEvents()).CallOriginalMethod();

    view.Expect(v => v.Username).Return("invalid").Repeat.Any();
    view.Expect(v => v.SubmitFail(null)).Constraints(Is.Same("Username is incorrect"));

    presenter.SetUp(view);
    presenter.SetUpEvents();

    view.Raise(v => v.Submit += null, null, EventArgs.Empty);

    presenter.VerifyAllExpectations();
    view.VerifyAllExpectations();
}

失败的期望是:

view.Expect(v => v.SubmitFail(null)).Constraints(Is.Same("Username is incorrect"));

(由view.VerifyAllExpectations表示)

它表示该方法永远不会执行,但是当使用调试器时我可以单步执行并访问LogOn.View,调用SubmitFailure方法(使用该参数)并正确返回。

我无法解决缺少的问题,因为观察代码确实表明所有内容都是在正确的时间以正确的值执行的。

编辑:好的,所以我发布了代码,这就是我嘲笑LogOn类的原因,它依赖于外部数据提供者(我将其作为我不在乎它是如何工作的)。我的抱怨,我以为我让这个更清楚,但只是做得更糟!

1 个答案:

答案 0 :(得分:1)

LogOn类是您正在测试的系统,因此您不应该嘲笑它。您希望测试LogOn类在用户名无效的情况下的行为。您可以通过传入设置所需方案的模拟视图来确定正确的行为。尝试将测试更改为我在下面的测试。

[TestMethod]
public void LogonFailure()
{
    var presenter = new LogOn();
    var view = MockRepository.CreateMock<ILogOn>();

    view.Expect(v => v.Username).Return("invalid").Repeat.Any();
    view.Expect(v => v.SubmitFail(null)).Constraints(Is.Same("Username is incorrect"));

    presenter.Setup(view);

    view.Raise(v => v.Submit += null, null, EventArgs.Empty);

    view.VerifyAllExpectations();
}
相关问题