我可以执行以下操作来验证我的ErrorOccurred
课程的Consumer
事件是否已被提出:
using System;
using FakeItEasy;
using Microsoft.VisualStudio.TestTools.UnitTesting;
public interface IService
{
event EventHandler SomethingBadHappened;
}
class Consumer
{
private readonly IService service;
public Consumer(IService service)
{
this.service = service;
service.SomethingBadHappened += (sender, args) => RaiseErrorOccurred();
}
public event EventHandler ErrorOccurred;
protected virtual void RaiseErrorOccurred()
{
var handler = ErrorOccurred;
if (handler != null) handler(this, EventArgs.Empty);
}
}
[TestClass]
public class UnitTest1
{
[TestMethod]
public void TestMethod1()
{
var service = A.Fake<IService>();
var consumer = new Consumer(service);
bool eventWasRaised = false;
consumer.ErrorOccurred += (sender, args) => { eventWasRaised = true; };
service.SomethingBadHappened += Raise.WithEmpty();
Assert.IsTrue(eventWasRaised);
}
}
我想知道是否有更多的“Mocking Framework-y”方式。像下面这样的东西会很好:
var service = A.Fake<IService>();
var consumer = new Consumer(service);
service.SomethingBadHappened += Raise.WithEmpty();
consumer.ErrorOccurred.MustHaveHappened(/*yada yada/*);
答案 0 :(得分:7)
对于FakeItEasy对方法执行任何断言,该方法必须是可伪造的,并在假对象上定义。在这种情况下,consumer
是一个真实的&#34;对象,所以FakeItEasy无法知道它是否有任何作用。
还有另一种选择,但它是否更多&#34; Mocking Framework-y&#34;是否有争议。但它可能会吸引你。
创建假(在这种情况下为handler
)以收听ErrorOccurred
方法:
[TestMethod]
public void TestMethod2()
{
var service = A.Fake<IService>();
var consumer = new Consumer(service);
var handler = A.Fake<EventHandler>();
consumer.ErrorOccurred += handler;
service.SomethingBadHappened += Raise.WithEmpty();
A.CallTo(()=>handler.Invoke(A<object>._, A<EventArgs>._)).MustHaveHappened();
}
通过这种方式,您可以查看handler
是否被调用。可以进行简单的修改,以确保将呼叫设为specific number of times或certain arguments。
当然,如果您不关心调用该方法的次数或参数,因为handler
上只有一种感兴趣的方法,您可能会使用这个更简单的调用,它将匹配对处理程序的任何调用(可能是Invoke
):
A.CallTo(handler).MustHaveHappened();