Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying event handler code executed

I have code very similar to this but cannot work out how I test whether an event handler occured.

public class MyClass : MyAbstractClass
{ 
  IFileSystem FileSystem;

  public MyClass(IFileSystem myFileSys)
  {
    FileSystem = myFileSys;
    FileSystem.EventHit += new EventHandler(FileSystem_EventHit);
  }

  public void FileSystem_EventHit(object sender, EventArgs e)
  {
    //Testing base.OnOutput is not possible which I wont go into
    base.OnOutput("EventHit");
  }
}

Testing code is here:

    [Test]
    public void DoSomething_WhenCalled_EventFired()
    {
         var mock = new Moq.Mock<IFileSystem>();

         MyClass plugin = new MyClass (mock.Object);

         mock.Object.DoSomething();

         mock.Raise(x => x.EventHit += null, new EventArgs());

        //Verify/Assert that MyClass handled and did something in the event handler

    }
like image 932
Jon Avatar asked Jun 05 '26 11:06

Jon


1 Answers

The simplest way I can think of is to just add your own handler in the test method, which should suffice I would think?

[Test]
    public void DoSomething_WhenCalled_EventFired()
    {
         var mock = new Moq.Mock<IFileSystem>();
         bool isHit = false;

         mock.EventHit += (s, e) =>
         {
            isHit = true;
         };

         MyClass plugin = new MyClass (mock.Object);

         mock.Object.DoSomething();

         mock.Raise(x => x.EventHit += null, new EventArgs());

         Assert.IsTrue(isHit);

    }
like image 96
Steve Danner Avatar answered Jun 08 '26 01:06

Steve Danner