¿ªÔÆÌåÓý

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

Re: [TDD] Statics and caches and mocks oh my!


 

I would avoid the statics, replace the references to the repositories with
interfaces, and also split the responsibility to cache or access data into
two pieces, so that each can be tested (and evolve) independently. For
more on this last part, see my article series on the CachedRepository
pattern:



If you happen to have a Pluralsight subscription (or grab the free trial)
there's a 6 minute demo showing this implementation as part of the Proxy
Design Pattern course, here:


Cheers,
Steve


On Wed, Jun 26, 2013 at 10:52 AM, David Burstin <david.burstin@...>wrote:

**


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

[Non-text portions of this message have been removed]




--
Steve Smith

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