无法在xUnit中捕获InvalidOperationException

问题描述 投票:0回答:1

我最近一小时一直在尝试通过以下测试,但我似乎无法使其通过:

[Fact]
public async void TestDetachedRecordsArentUpdatedWithoutIDs()
{
    var options = new DbContextOptionsBuilder<ClientContext>()
        .UseInMemoryDatabase(databaseName: "cant_update_detached_clients_with_bankinfos")
        .Options;

    int clientID, bankInfoID;
    using(var context = new ClientContext(options))
    {
        var service = new ClientService(context);
        var bankInfo = new BankInfo { RoutingNumber = "12345" };
        var client = new Client { FirstName = "Javier", LastName = "Garcia", BankInfo = bankInfo };
        await service.Save(client);
        clientID = client.ID;
        bankInfoID = client.BankInfo.ID;
    }

    using(var context = new ClientContext(options))
    {
        var service = new ClientService(context);
        var bankInfo = new BankInfo { RoutingNumber = "Modified" };
        var client = new Client { ID = clientID, FirstName = "Modified", BankInfo = bankInfo };

        try
        {
            await service.Save(client);
        }
        catch (System.InvalidOperationException ex)
        {
            var expected = "The property 'ID' on entity type 'BankInfo' is part of a key and so cannot be modified or marked as modified.";
            Assert.Contains(expected, ex.Message);
        }
    }
}

我发现的问题是我似乎无法捕捉到异常。这是我每次运行时的测试结果:

“

[提供一些额外的上下文,当调用ClientService::Save时,它将调用一个名为HandleDisconnectedEntities的方法,该方法在下一行运行时会爆炸:

94:  _context.Entry(existingClient.BankInfo).CurrentValues.SetValues(client.BankInfo);

我确实了解异常的性质,但是我不明白为什么我的测试无法捕获它。非常感谢任何见识!

c# .net-core entity-framework-core xunit
1个回答
1
投票

由于测试定义的async void而引起的问题。

© www.soinside.com 2019 - 2024. All rights reserved.