简体   繁体   中英

raise event Action in moq

I have structure as below. I want to test if LoadData is called when ViewLoaded event is triggered.

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()
    {

    }
}

Currently I have test like below, but it is not working. It states that LoadData is never called.

[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());
    }
}

It seems that I just needed to create controller.Object before raising event:

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

Setting the event handler happens in the constructor, which isn't called if you're only mocking the object.

In a unit test, you have one concrete class. Its dependencies are what you'd mock. Mocking them both basically only tests the mocking framework, not your class.

Since you want to test whether LoadData is called, you're probably interested if the event handler is set to LoadData. That LoadData is actually called when the event is raised is a given, unless you doubt the .NET framework itself.

This question discusses verifying whether an event has a specific subscriber. But it requires reflection and is not easy.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM