I am trying to create a test case where I need to set an attribute on the mocked object. I've been following the answer in this question but the attribute is null in the CommandEventProcessingDecorator
method.
[Fact]
public void RaiseEvent_AfterCommandIsExecuted_WhenCommandIsAttributedWithRaiseEventEnabled()
{
var command = new FakeCommand();
Assert.IsAssignableFrom<ICommand>(command);
var eventProcessor = new Mock<IProcessEvents>(MockBehavior.Strict);
eventProcessor.Setup(x => x.Raise(command));
var attribute = new RaiseEventAttribute
{
Enabled = true
};
var decorated = new Mock<IHandleCommand<FakeCommand>>(MockBehavior.Strict);
TypeDescriptor.AddAttributes(decorated.Object, attribute); // Add the attribute
decorated.Setup(x => x.Handle(command));
var decorator = new CommandEventProcessingDecorator<FakeCommand>(eventProcessor.Object, () => decorated.Object);
decorator.Handle(command);
decorated.Verify(x => x.Handle(command), Times.Once);
eventProcessor.Verify(x => x.Raise(command), Times.Once);
}
internal sealed class CommandEventProcessingDecorator<TCommand> : IHandleCommand<TCommand> where TCommand : ICommand
{
private readonly IProcessEvents _events;
private readonly Func<IHandleCommand<TCommand>> _handlerFactory;
public CommandEventProcessingDecorator(IProcessEvents events, Func<IHandleCommand<TCommand>> handlerFactory)
{
_events = events;
_handlerFactory = handlerFactory;
}
public void Handle(TCommand command)
{
var handler = _handlerFactory();
handler.Handle(command);
var attribute = handler.GetType().GetCustomAttribute<RaiseEventAttribute>(); // attribute
if (attribute != null && attribute.Enabled)
{
_events.Raise(command);
}
}
}
What am I doing wrong?