title: Proper way of testing ASP.NET Core IMemoryCache
body: <p>I'm writing a simple test case that tests that my controller calls the cache before calling my service. I'm using xUnit and Moq for the task.</p>
  
  <p>I'm facing an issue because <code>GetOrCreateAsync&lt;T&gt;</code> is an extension method, and those can't be mocked by the framework. I relied on internal details to figure out I can mock <code>TryGetValue</code> instead and get away with my test (see <a href="https://github.com/aspnet/Caching/blob/c432e5827e4505c05ac7ad8ef1e3bc6bf784520b/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L116" rel="noreferrer">https://github.com/aspnet/Caching/blob/c432e5827e4505c05ac7ad8ef1e3bc6bf784520b/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L116</a>)</p>
  
  <pre><code>[Theory, AutoDataMoq]
  public async Task GivenPopulatedCacheDoesntCallService(
      Mock&lt;IMemoryCache&gt; cache,
      SearchRequestViewModel input,
      MyViewModel expected)
  {
      object expectedOut = expected;
      cache
          .Setup(s =&gt; s.TryGetValue(input.Serialized(), out expectedOut))
          .Returns(true);
      var sut = new MyController(cache.Object, Mock.Of&lt;ISearchService&gt;());
      var actual = await sut.Search(input);
      Assert.Same(expected, actual);
  }
  </code></pre>
  
  <p>I can't sleep with the fact that I'm peeking into the MemoryCache implementation details and it can change at any point.</p>
  
  <p>For reference, this is the SUT code:</p>
  
  <pre><code>public async Task&lt;MyViewModel&gt; Search(SearchRequestViewModel request)
  {
      return await cache.GetOrCreateAsync(request.Serialized(), (e) =&gt; search.FindAsync(request));
  }
  </code></pre>
  
  <p>Would you recommend testing any differently?</p>