Testing event handlers in XUnit can be done through the Assert.Raises method. This method expect 3 parameters:
- An action of EventHandler<T> to attach a handler
- An action of EventHandler<T> to detach the handler
- An action containing the code that should trigger the event
This was not immediately clear to me so here is a (simple) example:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
[Fact] | |
public void NotCompletingAUnitOfWork_Triggers_FailedEvent() | |
{ | |
//Arrange | |
var unitOfWorkFactory = _container.Resolve<IUnitOfWorkFactory>(); | |
var queryFactory = _container.Resolve<IQueryFactory>(); | |
//Act | |
var uow = unitOfWorkFactory.Create(); | |
var customers = queryFactory | |
.Query("GetCustomers") | |
.List<Customer>(); | |
//Assert | |
Assert.Raises<UnitOfWorkFailedEventArgs>(handler => uow.Failed += handler, handler => uow.Failed -= handler, () => uow.Dispose()); | |
} |
And here is the interface of the IUnitOfWork that is tested above:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
public interface IUnitOfWork: IDisposable | |
{ | |
/// <summary> | |
/// This event is raised when this UOW is successfully completed. | |
/// </summary> | |
event EventHandler<UnitOfWorkCompletedEventArgs> Completed; | |
/// <summary> | |
/// This event is raised when this UOW is failed. | |
/// </summary> | |
event EventHandler<UnitOfWorkFailedEventArgs> Failed; | |
/// <summary> | |
/// Completes this unit of work. | |
/// It saves all changes and commit transaction if exists. | |
/// </summary> | |
void Complete(); | |
/// <summary> | |
/// Completes this unit of work. | |
/// It saves all changes and commit transaction if exists. | |
/// </summary> | |
Task CompleteAsync(); | |
} |