question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Unit testable code

See original GitHub issue

Hi folks, I would be interested in getting to know your opinion about making the library work in unit tests. Is there something I miss, or is it currently impossible to write unit tests for code that uses the library? E.g. I have my consuming code

   public class MetricLogger 
   {
        private static Counter _methodCallCounter = Prometheus.Metrics.CreateCounter(
            "ServiceName_call_count",
            "counter of calls", 
            new []{"method"});

        public void OnCalled(string key)
        {
            try
            {
                _methodCounter.Labels(key).Inc();
            }
            catch (Exception exc)
            {
                _logger.LogError(default, exc, "Could not log metric.");
            }
        }
  }

And now I want to unit test if the counter has been created and the Inc method has been called. There is no way to access the counters in the registry. Everything is hardwired to real implementations.

The solution here would be quite simple:

  • to give the CollectorRegistry an interface ICollectorRegistry
  • expose the registered Collector’s in the new ICollectorRegistry
  • allow MetricFactory to accept ICollectorRegistry instead of CollectorRegistry
  • to give the MetricFactory an interface IMetricFactory
  • extend Metrics with an option to set _defaultFactory from outside (eg. SetMetricFactoryForTests)

That would even enable me to remove the call to the static Metrics class in my consuming code and pass in a mockable IMetricFactory as constructor dependency.

If you think that makes sense, I could try to make PR. Regards, jbrekle

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:8 (4 by maintainers)

github_iconTop GitHub Comments

2reactions
janjuzacommented, Oct 24, 2022

HI, I would like to mock Counter class, nothing above is straightforward. I would like to test methods WithLabels() and Inc(), but they are not even in the same interface. Would it be possible replace result type Counter by some interface which would implement all other interfaces, to allow mock any method from all Counter’s interfaces? I think this could be ultimate solution for all mocking problems.

0reactions
DanielBryarscommented, Jun 22, 2021

Yeah the above isn’t going well for me, instead I’ve just made an IMetricsFactoryFactory, this means that in my libraries I don’t take a dependency on how the MetricsFactory is instantiated, but I do take a dependency on the concretes - which is fine:

`public class MetricFactoryFactory : IMetricFactoryFactory { private readonly CollectorRegistry _registry; private MetricFactory _metricFactory;

    public MetricFactoryFactory()
    {
        _registry = new CollectorRegistry();
        DotNetStats.Register(_registry);
        _metricFactory = Metrics.WithCustomRegistry(_registry);
    }

    public MetricFactory Create()
    {
        return _metricFactory;
    }
}`

MetricFactoryFactory : IMetricFactoryFactory is registered as a singleton in the DI by the process which consumes the library, and in tests you can make a custom registry if you want.

Read more comments on GitHub >

github_iconTop Results From Across the Web

Unit Testing and Coding: Why Testable Code Matters
In this article, I will show that unit testing itself is quite easy; the real problems that complicate unit testing, and introduce expensive...
Read more >
Writing Testable Code - SE-EDU/LearningResources
Writing Testable Code · Rule #1: Don't do Actual Work in Constructors · Rule #2: Don't Mix Object Construction With Application Logic ·...
Read more >
Writing Testable Code
Each unit should have only limited knowledge about other units : only units “closely” related to the current unit. Each unit should only...
Read more >
How to Write Testable Code | Khalil's Methodology
This works by placing an abstraction (interface or abstract class) in between the dependency you want to import and the source class. The...
Read more >
Writing code that is testable, maintainable, usable
Testing code means subjecting it to controlled input to verify it produces the expected outputs, and exhibits the expected behavior. There are ...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found