提升事件在moq中的行动

时间:2017-08-09 12:28:46

标签: c# unit-testing moq

我的结构如下。我想测试触发LoadData事件时是否调用ViewLoaded

public interface ISetupView
{
    event Action ViewLoaded;
}

public class BaseSetupController
{
    private ISetupView view;

    public BaseSetupController(ISetupView view)
    {
        this.view = view;
        view.ViewLoaded += () => { LoadData(); };
    }

    public virtual void LoadData()
    {

    }
}

目前我的测试如下,但它不起作用。它声明永远不会调用LoadData

[TestFixture]
public class BaseSetupControllerTests
{
    [Test]
    public void ViewLoad_LoadDataIsCalled()
    {
        Mock<ISetupView> view = new Mock<ISetupView>();
        Mock<BaseSetupController> controller = new Mock<BaseSetupController>(view.Object);
        controller.Setup(x => x.LoadData());
        view.Raise(x => x.ViewLoaded += () => { });
        controller.Verify(x=>x.LoadData(), Times.Once());
    }
}

2 个答案:

答案 0 :(得分:0)

似乎我只需要在举起活动之前创建controller.Object

var obj = controller.Object;
view.Raise(x=>x.ViewLoaded+=null);

答案 1 :(得分:0)

设置事件处理程序发生在构造函数中,如果您只是模拟对象,则不会调用它。

在单元测试中,您有一个具体的类。它的依赖性是你嘲笑的。 嘲笑它们基本上只测试模拟框架,而不是你的类。

由于您要测试是否调用了LoadData,因此如果事件处理程序设置为LoadData,您可能会感兴趣。除非您怀疑.NET框架本身,否则在引发事件时实际调用LoadData是一个给定的。

This question discusses verifying whether an event has a specific subscriber.但它需要反思并不容易。