listener 和 mutator 的角色有时可以组合在同一个类中(例如在适配器中),但不应将这两个角色一起测试。
在一项测试中,您只需验证您的听力课程是否PropertyChanged
按设计对事件做出反应。您不关心是什么导致该测试中的属性发生变化:
[Test]
public void Updates_Caption_when_Bar_PropertyChanged()
{
var foo = MockRepository.GenerateStub<IFoo>();
foo.Bar = "sometestvalue1";
var underTest = new UnderTest(foo);
// change property and raise PropertyChanged event on mock object
foo.Bar = "sometestvalue2";
foo.Raise(x=>x.PropertyChanged+=null,
foo,
new PropertyChangedEventArgs("Bar"));
// assert that the class under test reacted as designed
Assert.AreEqual("sometestvalue2", underTest.Caption);
// or if the the expected state change is hard to verify,
// you might just verify that the property was at least read
foo.AssertWasCalled(x => { var y = foo.Bar; } );
}
在另一个测试中,您验证您的类是否按设计发挥了它的 mutator 角色:
[Test]
public void Reset_clears_Foo_Bar()
{
var foo = MockRepository.GenerateStub<IFoo>();
foo.Bar = "some string which is not null";
var underTest = new UnderTest(foo);
underTest.Reset();
// assert that the class under test updated the Bar property as designed
Assert.IsNull(foo.Bar);
}
这样,就不需要像您尝试做的那样将真正的逻辑放入您的模拟对象中。这确实需要您为可测试性设计类;很难将这样的测试添加到现有的类中。因此,测试驱动开发的实践。