【问题标题】:How to test a private asynchronous function如何测试私有异步函数
【发布时间】:2020-11-16 22:07:15
【问题描述】:

我有一个MessageHandler,它有:

public void OnMessageReceived(object sender, Message e) {
       if (e.Type == speed ){
                var action = new Action (async ()=> await ProcessMessage(containerId, msgType, bytes).ConfigureAwait(false));
                action.BeginInvoke(action.EndInvoke, null);
       }
}

ProcessMessage 在哪里

 private async Task ProcessMessage(string containerId, MessageType messageType, byte[] data)
        {
            switch (messageType)
            {
                case MessageType.Fast:
                    await HandleFast(containerId, data);
                    break;
                case MessageType.Slow:
                    await HandleSlow(containerId, data);
                    break;
                case MessageType.Continuous:
                    await HandleContinuous(containerId, data);
                    break;
                case MessageType.Unknown:
                    break;
                default:
                    throw new ArgumentOutOfRangeException(nameof(messageType));
            }
        }

。 每个HandleXYZ 都是这样的:

private async Task HandleFast(string containerId, byte[] data)
        {
            if (!TryDeserializeObject(data, out Message msg)
            {
                return;
            }
            await _dataAccess.UpsertFastAsync(containerId, tenantId, msg);
        }

我想测试在给定消息类型的情况下是否调用了正确的UpsertXYZ。我试过的是:

  1. MessageHandler 上的垫片 - 如果调用了正确的函数,垫片中的标志会更新。不幸的是,无法测试调用了哪个函数,因为我要测试的所有异步行为都在 OnNewMessageReceived 层下,并且我无法在同步函数上调用 await
  2. Mut.PrivateObject MessageHandler- 通过创建 PrivateObject 来调用 ProcessMessage。找不到方法来确定是否调用了正确的 HandleXYZ
  3. 模拟/起订量 - 不能起订量私人功能...

如果给定 messageType,我如何测试正确的 UpsertXYZ 是否被调用?

【问题讨论】:

  • 你能模拟数据访问层吗?并检查是否以这种方式调用了正确的函数?例如使用 NSubstitute(对不起,我知道 atm)你可以检查函数是否被调用,即 _dataAccessMock.UpsertFastAsync(Args.Any).ReceivedCalls()。等等等等。它不再是一个真正的单元测试,但仍然可以实现你想要的?

标签: c# .net unit-testing async-await


【解决方案1】:

您不会模拟私有函数,但正如@Heinrich 所说,您可以模拟数据访问层并检查是否通过 MOQ 的验证函数调用了正确的函数

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-02-08
    • 2015-04-25
    • 2018-06-30
    • 1970-01-01
    • 1970-01-01
    • 2012-08-22
    • 1970-01-01
    相关资源
    最近更新 更多