XUnit how to mock IMemoryCache ASP.NET Core









up vote
0
down vote

favorite












I understand IMemoryCache.Set is an extension method so it can not be mocked. People have provided workarounds to such situation e.g as one by the NKosi here. I am wondering how I can achieve that for my data access layer where my MemoryCache returns a value and when not found it gets data from the db, set it to the MemoryCache and return the required value.



 public string GetMessage(int code)

if(myMemoryCache.Get("Key") != null)

var messages= myMemoryCache.Get<IEnumerable<MyModel>>("Key");
return messages.Where(x => x.Code == code).FirstOrDefault().Message;


using (var connection = dbFactory.CreateConnection())

var cacheOptions = new MemoryCacheEntryOptions SlidingExpiration = TimeSpan.FromHours(1) ;
const string sql = @"SELECT Code, Message FROM MyTable";

var keyPairValueData = connection.Query<KeyPairValueData>(sql);

myMemoryCache.Set("Key", keyPairValueData, cacheOptions );

return keyPairValueData.Where(x => x.Code == code).FirstOrDefault().Message;




Following is my Unit Test - And off course it is not working as I can't mock IMemoryCache



 [Fact]
public void GetMessage_ReturnsString()

//Arrange
// Inserting some data here to the InMemoryDB

var memoryCacheMock = new Mock<IMemoryCache>();

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memoryCacheMock.Object).GetMessage(1000);

//assert xunit
Assert.Equal("Some message", result);










share|improve this question





















  • Trying to fully mock that interface is tricky because of all the extensions used. That is why I started suggesting the use if the actual memory cache in the linked answer.
    – Nkosi
    Nov 9 at 11:30










  • What is the problem with the current test
    – Nkosi
    Nov 9 at 12:20










  • Object reference not set to an instance of an object error at the myMemoryCache.Set("Key", keyPairValueData, cacheOptions );
    – Learning Curve
    Nov 9 at 12:45











  • And have you tried using the approach from the linked answer?
    – Nkosi
    Nov 9 at 12:51










  • Creating a new instance of MemoryCache rather mocking works perfectly fine and I already had that done but wasn't sure if should be using actual objects rather mocks. So on that note first suggestion by @Kenneth works perfectly fine. Haven't tried his mocking suggestion yet though.
    – Learning Curve
    Nov 9 at 13:07














up vote
0
down vote

favorite












I understand IMemoryCache.Set is an extension method so it can not be mocked. People have provided workarounds to such situation e.g as one by the NKosi here. I am wondering how I can achieve that for my data access layer where my MemoryCache returns a value and when not found it gets data from the db, set it to the MemoryCache and return the required value.



 public string GetMessage(int code)

if(myMemoryCache.Get("Key") != null)

var messages= myMemoryCache.Get<IEnumerable<MyModel>>("Key");
return messages.Where(x => x.Code == code).FirstOrDefault().Message;


using (var connection = dbFactory.CreateConnection())

var cacheOptions = new MemoryCacheEntryOptions SlidingExpiration = TimeSpan.FromHours(1) ;
const string sql = @"SELECT Code, Message FROM MyTable";

var keyPairValueData = connection.Query<KeyPairValueData>(sql);

myMemoryCache.Set("Key", keyPairValueData, cacheOptions );

return keyPairValueData.Where(x => x.Code == code).FirstOrDefault().Message;




Following is my Unit Test - And off course it is not working as I can't mock IMemoryCache



 [Fact]
public void GetMessage_ReturnsString()

//Arrange
// Inserting some data here to the InMemoryDB

var memoryCacheMock = new Mock<IMemoryCache>();

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memoryCacheMock.Object).GetMessage(1000);

//assert xunit
Assert.Equal("Some message", result);










share|improve this question





















  • Trying to fully mock that interface is tricky because of all the extensions used. That is why I started suggesting the use if the actual memory cache in the linked answer.
    – Nkosi
    Nov 9 at 11:30










  • What is the problem with the current test
    – Nkosi
    Nov 9 at 12:20










  • Object reference not set to an instance of an object error at the myMemoryCache.Set("Key", keyPairValueData, cacheOptions );
    – Learning Curve
    Nov 9 at 12:45











  • And have you tried using the approach from the linked answer?
    – Nkosi
    Nov 9 at 12:51










  • Creating a new instance of MemoryCache rather mocking works perfectly fine and I already had that done but wasn't sure if should be using actual objects rather mocks. So on that note first suggestion by @Kenneth works perfectly fine. Haven't tried his mocking suggestion yet though.
    – Learning Curve
    Nov 9 at 13:07












up vote
0
down vote

favorite









up vote
0
down vote

favorite











I understand IMemoryCache.Set is an extension method so it can not be mocked. People have provided workarounds to such situation e.g as one by the NKosi here. I am wondering how I can achieve that for my data access layer where my MemoryCache returns a value and when not found it gets data from the db, set it to the MemoryCache and return the required value.



 public string GetMessage(int code)

if(myMemoryCache.Get("Key") != null)

var messages= myMemoryCache.Get<IEnumerable<MyModel>>("Key");
return messages.Where(x => x.Code == code).FirstOrDefault().Message;


using (var connection = dbFactory.CreateConnection())

var cacheOptions = new MemoryCacheEntryOptions SlidingExpiration = TimeSpan.FromHours(1) ;
const string sql = @"SELECT Code, Message FROM MyTable";

var keyPairValueData = connection.Query<KeyPairValueData>(sql);

myMemoryCache.Set("Key", keyPairValueData, cacheOptions );

return keyPairValueData.Where(x => x.Code == code).FirstOrDefault().Message;




Following is my Unit Test - And off course it is not working as I can't mock IMemoryCache



 [Fact]
public void GetMessage_ReturnsString()

//Arrange
// Inserting some data here to the InMemoryDB

var memoryCacheMock = new Mock<IMemoryCache>();

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memoryCacheMock.Object).GetMessage(1000);

//assert xunit
Assert.Equal("Some message", result);










share|improve this question













I understand IMemoryCache.Set is an extension method so it can not be mocked. People have provided workarounds to such situation e.g as one by the NKosi here. I am wondering how I can achieve that for my data access layer where my MemoryCache returns a value and when not found it gets data from the db, set it to the MemoryCache and return the required value.



 public string GetMessage(int code)

if(myMemoryCache.Get("Key") != null)

var messages= myMemoryCache.Get<IEnumerable<MyModel>>("Key");
return messages.Where(x => x.Code == code).FirstOrDefault().Message;


using (var connection = dbFactory.CreateConnection())

var cacheOptions = new MemoryCacheEntryOptions SlidingExpiration = TimeSpan.FromHours(1) ;
const string sql = @"SELECT Code, Message FROM MyTable";

var keyPairValueData = connection.Query<KeyPairValueData>(sql);

myMemoryCache.Set("Key", keyPairValueData, cacheOptions );

return keyPairValueData.Where(x => x.Code == code).FirstOrDefault().Message;




Following is my Unit Test - And off course it is not working as I can't mock IMemoryCache



 [Fact]
public void GetMessage_ReturnsString()

//Arrange
// Inserting some data here to the InMemoryDB

var memoryCacheMock = new Mock<IMemoryCache>();

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memoryCacheMock.Object).GetMessage(1000);

//assert xunit
Assert.Equal("Some message", result);







c# unit-testing mocking moq xunit






share|improve this question













share|improve this question











share|improve this question




share|improve this question










asked Nov 9 at 9:46









Learning Curve

61231534




61231534











  • Trying to fully mock that interface is tricky because of all the extensions used. That is why I started suggesting the use if the actual memory cache in the linked answer.
    – Nkosi
    Nov 9 at 11:30










  • What is the problem with the current test
    – Nkosi
    Nov 9 at 12:20










  • Object reference not set to an instance of an object error at the myMemoryCache.Set("Key", keyPairValueData, cacheOptions );
    – Learning Curve
    Nov 9 at 12:45











  • And have you tried using the approach from the linked answer?
    – Nkosi
    Nov 9 at 12:51










  • Creating a new instance of MemoryCache rather mocking works perfectly fine and I already had that done but wasn't sure if should be using actual objects rather mocks. So on that note first suggestion by @Kenneth works perfectly fine. Haven't tried his mocking suggestion yet though.
    – Learning Curve
    Nov 9 at 13:07
















  • Trying to fully mock that interface is tricky because of all the extensions used. That is why I started suggesting the use if the actual memory cache in the linked answer.
    – Nkosi
    Nov 9 at 11:30










  • What is the problem with the current test
    – Nkosi
    Nov 9 at 12:20










  • Object reference not set to an instance of an object error at the myMemoryCache.Set("Key", keyPairValueData, cacheOptions );
    – Learning Curve
    Nov 9 at 12:45











  • And have you tried using the approach from the linked answer?
    – Nkosi
    Nov 9 at 12:51










  • Creating a new instance of MemoryCache rather mocking works perfectly fine and I already had that done but wasn't sure if should be using actual objects rather mocks. So on that note first suggestion by @Kenneth works perfectly fine. Haven't tried his mocking suggestion yet though.
    – Learning Curve
    Nov 9 at 13:07















Trying to fully mock that interface is tricky because of all the extensions used. That is why I started suggesting the use if the actual memory cache in the linked answer.
– Nkosi
Nov 9 at 11:30




Trying to fully mock that interface is tricky because of all the extensions used. That is why I started suggesting the use if the actual memory cache in the linked answer.
– Nkosi
Nov 9 at 11:30












What is the problem with the current test
– Nkosi
Nov 9 at 12:20




What is the problem with the current test
– Nkosi
Nov 9 at 12:20












Object reference not set to an instance of an object error at the myMemoryCache.Set("Key", keyPairValueData, cacheOptions );
– Learning Curve
Nov 9 at 12:45





Object reference not set to an instance of an object error at the myMemoryCache.Set("Key", keyPairValueData, cacheOptions );
– Learning Curve
Nov 9 at 12:45













And have you tried using the approach from the linked answer?
– Nkosi
Nov 9 at 12:51




And have you tried using the approach from the linked answer?
– Nkosi
Nov 9 at 12:51












Creating a new instance of MemoryCache rather mocking works perfectly fine and I already had that done but wasn't sure if should be using actual objects rather mocks. So on that note first suggestion by @Kenneth works perfectly fine. Haven't tried his mocking suggestion yet though.
– Learning Curve
Nov 9 at 13:07




Creating a new instance of MemoryCache rather mocking works perfectly fine and I already had that done but wasn't sure if should be using actual objects rather mocks. So on that note first suggestion by @Kenneth works perfectly fine. Haven't tried his mocking suggestion yet though.
– Learning Curve
Nov 9 at 13:07












1 Answer
1






active

oldest

votes

















up vote
0
down vote



accepted










The first thing I would say is why not use a real memory cache? It would verify the behavior much better and there's no need to mock it:



// Arrange
var memCache = new MemoryCache("name", new NameValueCollection());

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memCache).GetMessage(1000);

// Assert: has been added to cache
memCache.TryGetValue("Key", out var result2);
Assert.Equal("Some message", result2);

// Assert: value is returned
Assert.Equal("Some message", result);


If you really want to mock it out, here's a guide on how to do that:



Because it's an extension method, you need to make sure that it can be called as is. What happens in your case is that the extension method will call into the mock. Since you provide no expected behavior, it will probably fail.



You need to look at the code for the extension method, check what it accesses and then ensure that your mock complies with the expected behavior. The code is available here:
https://github.com/aspnet/Caching/blob/master/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L77



This is the code:



public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)

using (var entry = cache.CreateEntry(key))

if (options != null)

entry.SetOptions(options);


entry.Value = value;


return value;



So, from that, you can see that it accesses CreateEntyand expects an object from it. Then it calls SetOptions and assigns Value on the entry.



You could mock it like this:



var entryMock = new Mock<ICacheEntry>();
memoryCacheMock.Setup(m => m.CreateEntry(It.IsAny<object>())
.Returns(entryMock.Object);

// maybe not needed
entryMock.Setup(e => e.SetOptions(It.IsAny<MemoryCacheEntryOptions>())
...


When you do this, the extension method will be called on the mock and it will return the mocked entry. You can modify the implementation and make it do whatever you want.






share|improve this answer






















  • I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
    – Learning Curve
    Nov 9 at 11:14











  • No, I did mean "why not use a real memory cache"
    – Kenneth
    Nov 9 at 11:27










  • @Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
    – Nkosi
    Nov 9 at 11:35










  • Good catch, updated the code
    – Kenneth
    Nov 9 at 13:43










  • Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
    – Kenneth
    Nov 9 at 13:59










Your Answer






StackExchange.ifUsing("editor", function ()
StackExchange.using("externalEditor", function ()
StackExchange.using("snippets", function ()
StackExchange.snippets.init();
);
);
, "code-snippets");

StackExchange.ready(function()
var channelOptions =
tags: "".split(" "),
id: "1"
;
initTagRenderer("".split(" "), "".split(" "), channelOptions);

StackExchange.using("externalEditor", function()
// Have to fire editor after snippets, if snippets enabled
if (StackExchange.settings.snippets.snippetsEnabled)
StackExchange.using("snippets", function()
createEditor();
);

else
createEditor();

);

function createEditor()
StackExchange.prepareEditor(
heartbeatType: 'answer',
convertImagesToLinks: true,
noModals: true,
showLowRepImageUploadWarning: true,
reputationToPostImages: 10,
bindNavPrevention: true,
postfix: "",
imageUploader:
brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
allowUrls: true
,
onDemand: true,
discardSelector: ".discard-answer"
,immediatelyShowMarkdownHelp:true
);



);













draft saved

draft discarded


















StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53223316%2fxunit-how-to-mock-imemorycache-asp-net-core%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown

























1 Answer
1






active

oldest

votes








1 Answer
1






active

oldest

votes









active

oldest

votes






active

oldest

votes








up vote
0
down vote



accepted










The first thing I would say is why not use a real memory cache? It would verify the behavior much better and there's no need to mock it:



// Arrange
var memCache = new MemoryCache("name", new NameValueCollection());

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memCache).GetMessage(1000);

// Assert: has been added to cache
memCache.TryGetValue("Key", out var result2);
Assert.Equal("Some message", result2);

// Assert: value is returned
Assert.Equal("Some message", result);


If you really want to mock it out, here's a guide on how to do that:



Because it's an extension method, you need to make sure that it can be called as is. What happens in your case is that the extension method will call into the mock. Since you provide no expected behavior, it will probably fail.



You need to look at the code for the extension method, check what it accesses and then ensure that your mock complies with the expected behavior. The code is available here:
https://github.com/aspnet/Caching/blob/master/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L77



This is the code:



public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)

using (var entry = cache.CreateEntry(key))

if (options != null)

entry.SetOptions(options);


entry.Value = value;


return value;



So, from that, you can see that it accesses CreateEntyand expects an object from it. Then it calls SetOptions and assigns Value on the entry.



You could mock it like this:



var entryMock = new Mock<ICacheEntry>();
memoryCacheMock.Setup(m => m.CreateEntry(It.IsAny<object>())
.Returns(entryMock.Object);

// maybe not needed
entryMock.Setup(e => e.SetOptions(It.IsAny<MemoryCacheEntryOptions>())
...


When you do this, the extension method will be called on the mock and it will return the mocked entry. You can modify the implementation and make it do whatever you want.






share|improve this answer






















  • I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
    – Learning Curve
    Nov 9 at 11:14











  • No, I did mean "why not use a real memory cache"
    – Kenneth
    Nov 9 at 11:27










  • @Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
    – Nkosi
    Nov 9 at 11:35










  • Good catch, updated the code
    – Kenneth
    Nov 9 at 13:43










  • Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
    – Kenneth
    Nov 9 at 13:59














up vote
0
down vote



accepted










The first thing I would say is why not use a real memory cache? It would verify the behavior much better and there's no need to mock it:



// Arrange
var memCache = new MemoryCache("name", new NameValueCollection());

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memCache).GetMessage(1000);

// Assert: has been added to cache
memCache.TryGetValue("Key", out var result2);
Assert.Equal("Some message", result2);

// Assert: value is returned
Assert.Equal("Some message", result);


If you really want to mock it out, here's a guide on how to do that:



Because it's an extension method, you need to make sure that it can be called as is. What happens in your case is that the extension method will call into the mock. Since you provide no expected behavior, it will probably fail.



You need to look at the code for the extension method, check what it accesses and then ensure that your mock complies with the expected behavior. The code is available here:
https://github.com/aspnet/Caching/blob/master/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L77



This is the code:



public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)

using (var entry = cache.CreateEntry(key))

if (options != null)

entry.SetOptions(options);


entry.Value = value;


return value;



So, from that, you can see that it accesses CreateEntyand expects an object from it. Then it calls SetOptions and assigns Value on the entry.



You could mock it like this:



var entryMock = new Mock<ICacheEntry>();
memoryCacheMock.Setup(m => m.CreateEntry(It.IsAny<object>())
.Returns(entryMock.Object);

// maybe not needed
entryMock.Setup(e => e.SetOptions(It.IsAny<MemoryCacheEntryOptions>())
...


When you do this, the extension method will be called on the mock and it will return the mocked entry. You can modify the implementation and make it do whatever you want.






share|improve this answer






















  • I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
    – Learning Curve
    Nov 9 at 11:14











  • No, I did mean "why not use a real memory cache"
    – Kenneth
    Nov 9 at 11:27










  • @Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
    – Nkosi
    Nov 9 at 11:35










  • Good catch, updated the code
    – Kenneth
    Nov 9 at 13:43










  • Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
    – Kenneth
    Nov 9 at 13:59












up vote
0
down vote



accepted







up vote
0
down vote



accepted






The first thing I would say is why not use a real memory cache? It would verify the behavior much better and there's no need to mock it:



// Arrange
var memCache = new MemoryCache("name", new NameValueCollection());

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memCache).GetMessage(1000);

// Assert: has been added to cache
memCache.TryGetValue("Key", out var result2);
Assert.Equal("Some message", result2);

// Assert: value is returned
Assert.Equal("Some message", result);


If you really want to mock it out, here's a guide on how to do that:



Because it's an extension method, you need to make sure that it can be called as is. What happens in your case is that the extension method will call into the mock. Since you provide no expected behavior, it will probably fail.



You need to look at the code for the extension method, check what it accesses and then ensure that your mock complies with the expected behavior. The code is available here:
https://github.com/aspnet/Caching/blob/master/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L77



This is the code:



public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)

using (var entry = cache.CreateEntry(key))

if (options != null)

entry.SetOptions(options);


entry.Value = value;


return value;



So, from that, you can see that it accesses CreateEntyand expects an object from it. Then it calls SetOptions and assigns Value on the entry.



You could mock it like this:



var entryMock = new Mock<ICacheEntry>();
memoryCacheMock.Setup(m => m.CreateEntry(It.IsAny<object>())
.Returns(entryMock.Object);

// maybe not needed
entryMock.Setup(e => e.SetOptions(It.IsAny<MemoryCacheEntryOptions>())
...


When you do this, the extension method will be called on the mock and it will return the mocked entry. You can modify the implementation and make it do whatever you want.






share|improve this answer














The first thing I would say is why not use a real memory cache? It would verify the behavior much better and there's no need to mock it:



// Arrange
var memCache = new MemoryCache("name", new NameValueCollection());

//Act
var result = new DataService(dbConnectionFactoryMock.Object, memCache).GetMessage(1000);

// Assert: has been added to cache
memCache.TryGetValue("Key", out var result2);
Assert.Equal("Some message", result2);

// Assert: value is returned
Assert.Equal("Some message", result);


If you really want to mock it out, here's a guide on how to do that:



Because it's an extension method, you need to make sure that it can be called as is. What happens in your case is that the extension method will call into the mock. Since you provide no expected behavior, it will probably fail.



You need to look at the code for the extension method, check what it accesses and then ensure that your mock complies with the expected behavior. The code is available here:
https://github.com/aspnet/Caching/blob/master/src/Microsoft.Extensions.Caching.Abstractions/MemoryCacheExtensions.cs#L77



This is the code:



public static TItem Set<TItem>(this IMemoryCache cache, object key, TItem value, MemoryCacheEntryOptions options)

using (var entry = cache.CreateEntry(key))

if (options != null)

entry.SetOptions(options);


entry.Value = value;


return value;



So, from that, you can see that it accesses CreateEntyand expects an object from it. Then it calls SetOptions and assigns Value on the entry.



You could mock it like this:



var entryMock = new Mock<ICacheEntry>();
memoryCacheMock.Setup(m => m.CreateEntry(It.IsAny<object>())
.Returns(entryMock.Object);

// maybe not needed
entryMock.Setup(e => e.SetOptions(It.IsAny<MemoryCacheEntryOptions>())
...


When you do this, the extension method will be called on the mock and it will return the mocked entry. You can modify the implementation and make it do whatever you want.







share|improve this answer














share|improve this answer



share|improve this answer








edited Nov 9 at 13:59

























answered Nov 9 at 10:11









Kenneth

22.9k23967




22.9k23967











  • I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
    – Learning Curve
    Nov 9 at 11:14











  • No, I did mean "why not use a real memory cache"
    – Kenneth
    Nov 9 at 11:27










  • @Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
    – Nkosi
    Nov 9 at 11:35










  • Good catch, updated the code
    – Kenneth
    Nov 9 at 13:43










  • Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
    – Kenneth
    Nov 9 at 13:59
















  • I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
    – Learning Curve
    Nov 9 at 11:14











  • No, I did mean "why not use a real memory cache"
    – Kenneth
    Nov 9 at 11:27










  • @Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
    – Nkosi
    Nov 9 at 11:35










  • Good catch, updated the code
    – Kenneth
    Nov 9 at 13:43










  • Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
    – Kenneth
    Nov 9 at 13:59















I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
– Learning Curve
Nov 9 at 11:14





I believe you meant to say why to use a real memory cache rather "why not"? Please correct me if I am wrong!
– Learning Curve
Nov 9 at 11:14













No, I did mean "why not use a real memory cache"
– Kenneth
Nov 9 at 11:27




No, I did mean "why not use a real memory cache"
– Kenneth
Nov 9 at 11:27












@Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
– Nkosi
Nov 9 at 11:35




@Kenneth I believe the first snippet example is off as MemoryCache does not have a parameterless constructor.
– Nkosi
Nov 9 at 11:35












Good catch, updated the code
– Kenneth
Nov 9 at 13:43




Good catch, updated the code
– Kenneth
Nov 9 at 13:43












Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
– Kenneth
Nov 9 at 13:59




Ah, yeah, you're right. You need to change that to .Returns(entryMock.Object) because you want to return the instance, not the mock container. I've updated the answer
– Kenneth
Nov 9 at 13:59

















draft saved

draft discarded
















































Thanks for contributing an answer to Stack Overflow!


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.





Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


Please pay close attention to the following guidance:


  • Please be sure to answer the question. Provide details and share your research!

But avoid


  • Asking for help, clarification, or responding to other answers.

  • Making statements based on opinion; back them up with references or personal experience.

To learn more, see our tips on writing great answers.




draft saved


draft discarded














StackExchange.ready(
function ()
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53223316%2fxunit-how-to-mock-imemorycache-asp-net-core%23new-answer', 'question_page');

);

Post as a guest















Required, but never shown





















































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown

































Required, but never shown














Required, but never shown












Required, but never shown







Required, but never shown







Popular posts from this blog

𛂒𛀶,𛀽𛀑𛂀𛃧𛂓𛀙𛃆𛃑𛃷𛂟𛁡𛀢𛀟𛁤𛂽𛁕𛁪𛂟𛂯,𛁞𛂧𛀴𛁄𛁠𛁼𛂿𛀤 𛂘,𛁺𛂾𛃭𛃭𛃵𛀺,𛂣𛃍𛂖𛃶 𛀸𛃀𛂖𛁶𛁏𛁚 𛂢𛂞 𛁰𛂆𛀔,𛁸𛀽𛁓𛃋𛂇𛃧𛀧𛃣𛂐𛃇,𛂂𛃻𛃲𛁬𛃞𛀧𛃃𛀅 𛂭𛁠𛁡𛃇𛀷𛃓𛁥,𛁙𛁘𛁞𛃸𛁸𛃣𛁜,𛂛,𛃿,𛁯𛂘𛂌𛃛𛁱𛃌𛂈𛂇 𛁊𛃲,𛀕𛃴𛀜 𛀶𛂆𛀶𛃟𛂉𛀣,𛂐𛁞𛁾 𛁷𛂑𛁳𛂯𛀬𛃅,𛃶𛁼

Edmonton

Crossroads (UK TV series)