FusionCache icon indicating copy to clipboard operation
FusionCache copied to clipboard

Unit testing classes using IFusionCache is difficult due to reliance on extension methods

Open petriceko opened this issue 8 months ago • 4 comments

Hi 👋

I’m trying to write unit tests for a class that depends on IFusionCache.

The issue I’m facing is that most of the commonly used methods (like GetOrSetAsync, etc.) are implemented as extension methods in the NuGet package. Because of that:

  • These methods are static extension methods
  • They are not directly part of the IFusionCache interface
  • They cannot be mocked with standard mocking frameworks (e.g. Moq, NSubstitute, etc.)
  • It’s unclear which underlying interface method is actually being invoked internally

As a result, when I mock IFusionCache, my tests fail because the extension methods are not interceptable, and I don’t know which original interface method I should be setting up in my mock.

Would it be possible to move key methods into the interface instead of extension methods to improve mockability?

Regards

petriceko avatar Mar 30 '26 08:03 petriceko

Hi @petriceko , the core IFusionCache interface has basically only 1 "concrete method" per "logical method" (acctually 2: sync + async, but that's it).

What I mean is that, even if you have available dozens of different overloads, you just have to mock a single one among these:

  • TryGet()
  • GetOrDefault()
  • Set()
  • Remove()

The only exception to this is GetOrSet(), which has 2, so there you have to mock 2 of them, but that's it.

By doing this, any ext method will work with the mock.

You can see which one you have to mock by looking at the IFusionCache interface here.

Thoughts?

jodydonetti avatar Mar 30 '26 09:03 jodydonetti

Hi 👋

Thanks for the clarification.

I understand that internally there is only one “core” method per logical operation and that extension methods eventually delegate to those. However, from a consumer/testing perspective, this approach is not very friendly.

For example, in my unit test I tried to mock it like this:

private readonly IFusionCache _fusionCache = Substitute.For<IFusionCache>();
.
.
.
_fusionCache
    .GetOrSetAsync<int>(
        FullKey,
        Arg.Any<Func<FusionCacheFactoryExecutionContext<int>, CancellationToken, Task<int>>>(),
        Arg.Any<MaybeValue<int>>(),
        Arg.Any<FusionCacheEntryOptions>(),
        Arg.Any<IEnumerable<string>>(),
        Arg.Any<CancellationToken>())
    .Returns(42);

This resulted in a NullReferenceException because internal logic inside the extension method was still executed.

For clarification: even if I mock the 4 core methods you mentioned (TryGet, GetOrDefault, Set, Remove), in the background the method GetOrCreateDefaultEntryOptions is still invoked. Inside that method, a NullReferenceException occurs unless I additionally mock DefaultEntryOptions on IFusionCache.

So in practice:

  • The extension methods are not directly mockable since they are static.
  • Even when mocking the core methods, additional internal members (like DefaultEntryOptions) must also be mocked.
  • The test author must inspect the internal implementation to understand what else needs to be configured.
  • This couples unit tests to internal implementation details, which ideally should not be necessary.

While it is technically possible to mock the minimal set of core methods, in practice it requires knowledge of internal behavior that is not obvious from the public API interface.

For this reason, I still believe that moving commonly used methods like GetOrSetAsync into the interface (instead of relying on extension methods) would significantly improve testability and developer experience.

Thanks again for your time and clarification.

petriceko avatar Mar 30 '26 12:03 petriceko

Hi 👋 Just to add a small perspective here — I found the explanation helpful, and I can see the reasoning behind keeping the core surface minimal. That said, I did run into a similar experience when trying to unit test code using GetOrSetAsync. Even after setting up mocks for the main methods, I noticed that some additional configuration (like default options) was needed to avoid unexpected issues. It wasn’t immediately obvious from the public API, so it took a bit of digging to understand what was happening. Totally understand that extension methods help keep the interface lean, but from a consumer point of view, having some of the commonly used operations directly on the interface could make testing a bit more straightforward and reduce the need to be aware of internal behavior. Not a blocker of course, just sharing feedback from a usability/testing angle 🙂 Thanks again for the clarifications!

vikrantingole avatar Mar 30 '26 13:03 vikrantingole

Hi 👋 Also some small perspective, I usualy don't mock FusionCache. What I want is to test is the factory and if it behaves accordingly so what I usualy do is something like this

private static IFusionCache CreateFusionCache()
        {
            return new FusionCache(
                new FusionCacheOptions
                {
                    DisableTagging = true,
                    EnableSyncEventHandlersExecution = true,
                    DefaultEntryOptions = new FusionCacheEntryOptions
                    {
                        IsFailSafeEnabled = true
                    }
                },
                new MemoryCache(new MemoryCacheOptions()),
                NullLogger<FusionCache>.Instance,
                new NullMemoryLocker());
        }

Coelho04 avatar Apr 01 '26 12:04 Coelho04