我需要测试事件。 我在课堂上举办了一个活动,但我没有在考试中得到它。 是什么原因? Object_TransferInterruptedEvent1是较新的执行。 这是演示代码。
public class A
{
public virtual event EventHandler<EventArgs<Tuple<Step, string>>> TransferInterruptedEvent;
public void Test()
{
this.OnEventTransferInterrupted(this.CurrentStep, "Transfer not valid");
}
protected void OnEventTransferInterrupted(Step step, string errorMsg)
{
if (this.TransferInterruptedEvent != null)
{
this.TransferInterruptedEvent(this,new EventArgs<Tuple<object, string>>(new Tuple<object, string>(step, errorMsg)));
}
}
}
测试
var mock=new Mock<A>()
EventArgs<Tuple<S3Server.Step, string>> mess;
mock.Object.TransferInterruptedEvent += Object_TransferInterruptedEvent1;
mock.Object.Test();
Assert.IsTrue(mess.Value.Item1 == S3Server.Step.TransferValidation);
Assert.IsTrue(mess.Value.Item2 == "Transfer not valid");
private void Object_TransferInterruptedEvent1(object sender, EventArgs<Tuple<object, string>> e) {
mess=e;
}
答案 0 :(得分:1)
设置模拟以调用基类。通过设置mock.CallBase = true;
这将允许模拟框架分配事件订阅。
[TestMethod]
public void _MockEvent() {
//Arrange
var mock = new Mock<A>();
mock.CallBase = true;
EventArgs<Tuple<Step, string>> mess = null;
mock.Object.TransferInterruptedEvent += delegate(object sender, EventArgs<Tuple<Step, string>> e) {
mess = e;
};
//Act
mock.Object.Test();
//Assert
Assert.IsNotNull(mess);
Assert.IsTrue(mess.Value.Item1 == Step.TransferValidation);
Assert.IsTrue(mess.Value.Item2 == "Transfer not valid");
}