We are currently building an actor based system using Akka.NET. Creating the system itself is a breeze thanks to Akka.NET, but the introduction of the actor model and actors makes testing somewhat harder.
The scenario we struggled the most with is when an Actor executes a task but reports no message back. In that case we don’t know what happened inside the actor itself making it hard to assert what is going on. Anyway today I wanted to talk about another scenario; how to test if an Actor throws an Exception.
I couldn’t find a good example that showed how to handle this test case, so here is how we do it(any feedback is welcome):
Remark: We are using NUnit in combination with Akka.TestKit.NUnit.
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 class SampleActor:ReceiveActor | |
{ | |
public class Message{} | |
public SampleActor() | |
{ | |
Receive<SampleActor.Message>(message => DoSomething(message)); | |
} | |
private void DoSomething(SampleActor.Message message) | |
{ | |
throw new Exception(); | |
} | |
} |
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
[TestFixture] | |
public class SampleActorTests : TestKit | |
{ | |
[Test] | |
public void SampleActor_Should_Throw_An_Exception() | |
{ | |
//Arrange | |
var actor = Sys.ActorOf(Props.Create(() => new SampleActor())); | |
var filter = CreateEventFilter(Sys); | |
//Act & Assert | |
filter.Exception<Exception>().Expect(1,TimeSpan.FromSeconds(3), () => { actor.Tell(new SampleActor.Message()); }); | |
} | |
} |