1

I am unable to insert a cache entry in ObjectCache with Set in my unit tests.

var objectCache = Substitute.For<ObjectCache>();
objectCache.Set("TestKey", object, Arg.Any<DateTimeOffset>());

When I step into my code

var cachedData = _objectCache.Get("TestKey");
// cachedData is null

I am using Nsubstitute for mocking libraries.

Does anyone know how to overcome this issue?

Hichame Yessou
  • 2,658
  • 2
  • 18
  • 30
Songtham T.
  • 185
  • 1
  • 2
  • 15
  • 2
    You mock the Set on a mocked object. nothing is actually being saved in the mock. You need to mock the Get for that key in order to get the desired behavior – Nkosi Jan 24 '18 at 22:57
  • Not specifically related to the question, but using argument matchers as arguments to calls without `.Returns`/`.Received`/`.When`, such as `Set("TestKey", object, Arg.Any())` used in this question, can cause problems with tests. See the [docs](http://nsubstitute.github.io/help/argument-matchers/#how_not_to_use_argument_matchers) for more info. – David Tchepak Jan 25 '18 at 02:39

1 Answers1

4

You will need to configure the mock for the Get method. See the example for the return method in the NSubstitute docs.

Something like...

var objectCache = Substitute.For<ObjectCache>();
objectCache.Get("TestKey").Returns(...what you want it to return);
Matt Stannett
  • 2,700
  • 1
  • 15
  • 36