Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
namespace SemanticModelTest
{
[TestFixture]
public class ModelTest
{
[Test]
public void RaisesEvents()
{
// Act
var user = new User();
// Assert
Assert.That(user.Events, Has.Count.EqualTo(1));
}
[Test]
public void CannotRaiseUnknownEvent()
{
// Arrange
var user = new User();
// Act
try
{
user.RaiseUnknown();
// Assert
Assert.Fail("Should throw");
}
catch (UnknownEventException)
{
// expected
}
}
}
public class UnknownEventException : Exception
{
}
public abstract class ModelEvent
{
}
public abstract class DomainModel
{
protected DomainModel()
{
Events = new List<object>();
}
public List<object> Events { get; private set; }
protected void ApplyEvent(ModelEvent @event)
{
var stackTrace = new StackTrace();
var stackFrames = stackTrace.GetFrames();
if (stackFrames == null)
{
throw new ApplicationException("No stack frames available!");
}
foreach (var stackFrame in stackFrames)
{
var raisesEventsAttribute = (RaisesEventsAttribute)stackFrame.GetMethod().GetCustomAttribute(typeof(RaisesEventsAttribute));
if (raisesEventsAttribute != null && raisesEventsAttribute.Events.Any(x => x.IsInstanceOfType(@event)))
{
Events.Add(@event);
return;
}
}
throw new UnknownEventException();
}
}
public class RaisesEventsAttribute : Attribute
{
public RaisesEventsAttribute(params Type[] events)
{
Events = events;
}
public Type[] Events { get; private set; }
}
public class User : DomainModel
{
[RaisesEvents(typeof(UserCreatedEvent))]
public User()
{
ApplyEvent(new UserCreatedEvent());
}
public void RaiseUnknown()
{
ApplyEvent(new UnexpectedEvent());
}
}
public class UnexpectedEvent : ModelEvent
{
}
public class UserCreatedEvent : ModelEvent
{
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment