EventAccess

Abstract

Testing events can be dificult because c# requires that only the declaring class can invoke the method. I found a way around this problem for both abstract/interfaced and defined events. The trickery can be invoked via an EventAccess object.

Useful Functions

Fire

Fires the event which is accessed. If an event named MyEvent is accessed, then calling Fire() is equivalent to calling MyEvent().

Example

public class Connection
{
  public event Action ConnectionLost;
  public event Func<int, bool> DataSent;

  public bool Connected { get; set; }
  public int TotalBytesSent { get; set; }

  public Connection()
  {
    ConnectionLost += () => { Connected = false; };

    DataSent += (numBytes) => { TotalBytesSent += numBytes; return false; };
  }
}

public class ConnectionTest
{
  public void ConnectionLostTest()
  {
    var conn = ProxyManager.CreateProxy<Connection>();

    conn.Connected = true;

    var lostEventAccess = ProxyManager.GetEventAction(conn, "ConnectionLost");
    lostEventAccess.Fire();

    Assert.IsFalse(conn.Connected, "connected");

    var dataSentConfig = ProxyManager.GetEventFunc<int, bool>(conn, "DataSent");
    dataSentConfig.Fire(20);

    Assert.AreEqual(20, conn.TotalBytesSent, "TotalBytesSent");
  }
}

Last edited Apr 30, 2010 at 6:11 AM by payonel, version 2

Comments

No comments yet.