如何在测试方法中正确 运行 异步线程?

How to correctly run an async thread in a test method?

我有这个测试需要 运行 RunWebSocket 线程以确保我的 websocket 收到 SendAsync。这有效,但我收到编译器警告 CS4014。当然,我不喜欢警告,所以与其忽略它,不如“正确”地去做。

[Fact]
public async void CabinetTagPushed_ShouldSendBroadcastToWebSocket()
{
    // arrange
    var websocket = Substitute.For<IWebSocket>();
    restinterface.RunWebSocket(websocket);

    // act
    restinterface.Cabinet_OnTagPushed(null, new TagEventArgs());

    // assert
    await websocket.Received().SendAsync(Arg.Any<ArraySegment<byte>>(), WebSocketMessageType.Text, false, CancellationToken.None);

    // this will end the RunWebSocket thread
    websocket.CloseStatus = WebSocketCloseStatus.NormalClosure;
}

如何创建能够正确启动 async 线程的测试?

首先,你的单元测试方法必须是async Task,而不是async void

接下来,await 所有任务通常是个好主意,以确保您观察到异常情况。假设警告出现在 RunWebSocket 调用中,那么它看起来像这样:

[Fact]
public async Task CabinetTagPushed_ShouldSendBroadcastToWebSocket()
{
    // arrange
    var websocket = Substitute.For<IWebSocket>();
    var runTask = restinterface.RunWebSocket(websocket);

    // act
    restinterface.Cabinet_OnTagPushed(null, new TagEventArgs());

    // assert
    await websocket.Received().SendAsync(Arg.Any<ArraySegment<byte>>(), WebSocketMessageType.Text, false, CancellationToken.None);

    // this will end the RunWebSocket thread
    websocket.CloseStatus = WebSocketCloseStatus.NormalClosure;

    await runTask;
}