I am very new to ASP.NET and I am trying to write xunit tests for a cache class. This cache class is used for get some data and return the data in a web api controller. The cached data comes from some outside urls, where each cache item has its own cache key.
In my cache.cs class, I have a method called GetCacheGetOrCreateAsync(... cacheDataSetting), and in my controller I will call it to get the data I want. I implemented the cache using IMemoryCache class.
There is also a private method in cache.cs called GetDataByteArrayAsync(string url), in which I create a httpclient from IHttpClientFactory (it been injected to the cache.cs class level), and returns the outside data get by httpclient.
GetCacheGetOrCreateAsync(... cacheDataSetting) calls GetDataByteArrayAsync(string url) to get data and then cache it.
Now I want to write unit tests for GetCacheGetOrCreateAsync(... cacheDataSetting) (since it's the only public method in this class), and I want to mock the IHttpClientFactory and httpclient, but I'm confused about how can I actually use the mocked httpclient return value since GetCacheGetOrCreateAsync(... cacheDataSetting) calls GetDataByteArrayAsync(string url) directly. Should I make httpclient a formal parameter for GetCacheGetOrCreateAsync(... cacheDataSetting) method? What will be a universal practice for unit testing the cache behaviors?
Thank you!
I have tried to mock the IHttpClientFactory and httpclient, also tried to directly mock IMemoryCache but also found someone suggested we cannot mock cache directly using Moq. Super confused.