1

I have an analytics client that has a track method getting invoked when an event is received.

When I go to mock the class I get this:

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

Is there any way to spy on and verify parameters passed to a sealed class method?

in JUnit you can more freely do a "spyOn(class.method)..."

How can this be done in C# or with Moq?

Code looks like:

  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");
        }
    }

Current Unit test attempt:

    [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());
    }
heug
  • 982
  • 2
  • 11
  • 23
  • Heug can you add the code where you initialize _telemetry? It is a bit hard to talk about only knowing the variable name. Are you using dependency injection? – Kristian Barrett Aug 08 '19 at 21:19
  • @KristianBarrett its just regular private variable going into a constructor, but i added it – heug Aug 12 '19 at 16:44
  • `new Mock()` is not possible because `TelemetryClient` cannot be inherited from (it is a `sealed class`). Moq works only by inheriting (or implementing as it is called for interfaces) the relevant type and supplying new implementations for the methods/properties/etc. – Jeppe Stig Nielsen Aug 13 '19 at 21:39
  • @JeppeStigNielsen im aware, thats why i mentioned all of that above in the original post/question. im looking for solutions despite this. – heug Aug 14 '19 at 21:42

0 Answers0