mardi 22 octobre 2019

How to test async exceptions in Akka actor with a RecieveAsync

I have a try/catch block in both my application and unit test. I'm trying to create a test that catches an exception being thrown in my actor. When debugging through the code I get the exception being thrown but in my test I never receive the exception.

Application:

public FooActor(IFooService fooService, IChildActorFactory childCreatorFactory)     {   
        this.fooService = fooService;
        this.childCreatorFactory = childCreatorFactory;

        ReceiveAsync<bool>(async (x) => await StartAsync(x).ConfigureAwait(false));
    }

    protected override void PreStart() {
        barActor = childCreatorFactory.Create<BarActor>(Context, "BarActor");
    }

    public async Task StartAsync(bool start) {
        try {
            if (start) {
                var fooInformation = await fooService.GetInformationAsync().ConfigureAwait(false);

                if (fooInformation != null) {
                    barActor.Tell(fooInformation);
                }
            }
        } catch (Exception exception) {
            throw new Exception($"Unhandled Exception. Actor {Self.Path.Name};", exception);
        }
    }
}

Test:

[Fact]
public void StartAsync_ThrowsException_ExceptionThrown() {
    using (var mock = AutoMock.GetLoose()) {
        //Arrange
        Sys.UseAutofac(mock.Container);
        var mockChildActorFactory = mock.Mock<IChildActorFactory>();
        var mockBarService = mock.Mock<IBarService>();

        mockBarService.Setup(x => x.GetInformationAsync()).Throws(new Exception());

        var props = Props.Create(() => new FooActor(mockBarService.Object, mockChildActorFactory.Object));

        var fooActorName = "FooActor";
        var fooActor = new TestActorRef<FooActor>(Sys, props, null, fooActorName);

        try {
            // Act
            fooActor.Receive(true);
        } catch (Exception exception) {
            // Assert
            Assert.Equal($"Unhandled Exception. Actor { fooActorName }.", exception.Message);
        }
    }
}

Aucun commentaire:

Enregistrer un commentaire