首页 > 解决方案 > 如何监视密封库类中的方法?

问题描述

我有一个分析客户端,它在收到事件时调用了一个跟踪方法。

当我去模拟课堂时,我得到了这个:

 Type to mock must be an interface or an abstract or non-sealed class.

有没有办法监视和验证传递给密封类方法的参数?

在 JUnit 中,您可以更自由地执行“spyOn(class.method)...”

这如何在 C# 或 Moq 中完成?

代码如下:

  private readonly TelemetryClient _telemetry;

    public ClassToTest(TelemetryClient telemetry)
    {
        _telemetry = telemetry;
    }

 public async Task ProcessMessageAsync(EventMessage message, CancellationToken cancelToken)
    {
        try
        {
            var serviceNotificationEvent = JsonConvert.DeserializeObject<ServiceNotificationEvent>(message.Value);
            _telemetry.TrackEvent(AnalyticsConstants.EVENT_RECEIVED);

        }
        catch (Exception e)
        {
            _logger.LogError(e, "Error processing event message");
        }
    }

当前单元测试尝试:

    [TestMethod]
    public void Test_ReceivedEventAnalytic()
    {
        Mock<TelemetryClient> _mockTelemetry = new Mock<TelemetryClient>();

        _serviceNotificationProcessor.ProcessMessagesAsync(mockMessageList);
        IDictionary<String, String> matchingMap = new Dictionary<string, string>();
       // build out matchingMap

        _mockTelemetry.Verify(t => t.TrackEvent("seamEventReceived", It.IsAny<IDictionary<string, string>>(), null), Times.Once());
    }

标签: c#unit-testingmoqassertspy

解决方案


推荐阅读