¿ªÔÆÌåÓý

ctrl + shift + ? for shortcuts
© 2025 Groups.io

Statics and caches and mocks oh my!


 

Hi folks,

I've got a question around design for a legacy project that I am working on
in c#.

This project uses some repository classes that internally act as caches,
retrieving data from internal lists and only hitting the database if the
items are not found. These are all implemented as static methods -
effectively acting as globals. The static repositories provide the benefits
of global accessibility throughout the project as well as a single internal
long-lived cache.

My problem is that I am trying to test some classes that use these
repositories as collaborators, but don't have a good way of mocking/faking
the repositories as (a) they don't have any interfaces and (b) they are not
instances, so cannot be injected.

One option is to add static methods to the repositories to inject canned
data into their internal lists for testing, but that seems wrong to me - it
exposes their internal implementation and breaks encapsulation (is there
such a thing with static objects?).

Another is to create an interface and have the production code use a
concrete implementation that internally calls the static methods.In testing
I can inject mocks. Again, this seems messy to me.

I personally don't like the use of static objects, but I don't know what a
better alternative is that would provide long-lived caching and easy
accessibility from anywhere in the code. Everyone else on the team thinks
that they are a great solution.

What do you guys think? Is there a good way to test this scenario that I am
missing? Or is the design smelly as I suspect?

Cheers
David

Join [email protected] to automatically receive all group messages.