我正在使用JustMock编写一些单元测试,我很高兴他们都在通过,直到我试图让一个失败。本单元测试通过:
[TestFixture]
public class TestEventAggregation
{
class BaseEventArgs : EventArgs {}
class DerivedEventArgs : BaseEventArgs {}
class EventAggregationService
{
private Subject<object> _subject = new Subject<object>();
public IDisposable Subscribe<TEventArgs>(EventHandler<TEventArgs> eventHandler)
where TEventArgs : EventArgs
{
return _subject.OfType<EventPattern<TEventArgs>>().Subscribe(
delegate(EventPattern<TEventArgs> pattern)
{
eventHandler(pattern.Sender, pattern.EventArgs);
}
);
}
public void Publish<TEventArgs>(object sender, TEventArgs eventArgs)
where TEventArgs : EventArgs
{
_subject.OnNext(new EventPattern<TEventArgs>(sender, eventArgs));
}
}
[Test]
public void BaseEventIsPublishedToBaseEventSubcriberButNotDerivedEventSubscriber()
{
EventAggregationService eventAggregationService = new EventAggregationService();
// Arrange
Action<object, BaseEventArgs> baseEventHandler = Mock.Create<Action<object, BaseEventArgs>>();
Mock.Arrange(() => baseEventHandler(Arg.AnyObject, Arg.IsAny<BaseEventArgs>())).OccursOnce();
Action<object, DerivedEventArgs> derivedEventHandler = Mock.Create<Action<object, DerivedEventArgs>>();
Mock.Arrange(() => derivedEventHandler(Arg.AnyObject, Arg.IsAny<DerivedEventArgs>())).OccursOnce();
// Act
using (eventAggregationService.Subscribe(new EventHandler<BaseEventArgs>((s, e) => baseEventHandler(s, e))))
using (eventAggregationService.Subscribe(new EventHandler<DerivedEventArgs>((s, e) => derivedEventHandler(s, e))))
{
eventAggregationService.Publish(this, new BaseEventArgs());
}
// Assert
Mock.Assert(baseEventHandler);
Mock.Assert(derivedEventHandler);
}
}
它应该失败,我在每个lambda中都设置了一个断点,并且调用了base而不是派生的。我试过转移和扭曲的东西,但我不能为我的生活找出为什么这个测试通过,因为派生的处理程序被确认不被调用。
要自己构建,请添加对nunit,JustMock和Rx-Linq NuGet包的引用。
答案 0 :(得分:0)
作为一种变通方法,您可以显式声明对事件处理程序的调用:
Mock.Assert(() => baseEventHandler(null, null), Args.Ignore(), Occurs.Once());
Mock.Assert(() => derivedEventHandler(null, null), Args.Ignore(), Occurs.Never());