My Cache Class is given below:
public class InMemoryCache : ICache
{
private readonly ObjectCache _objCache = MemoryCache.Default;
public void Insert<T>(string cacheKey, T value)
{
_objCache.Add(cacheKey, value, DateTimeOffset.MaxValue);
}
public T Get<T>(string cacheKey)
{
if (cacheKey != null)
return (T)Convert.ChangeType(_objCache.Get(cacheKey), typeof(T));
else
return default(T);
}
public bool Exists<T>(string cacheKey)
{
return _objCache.Get(cacheKey) != null;
}
}
And my Interface is
public interface ICache
{
void Insert<T>(string cacheKey, T value);
T Get<T>(string cacheKey);
bool Exists<T>(string cacheKey);
}
I am using CacheFactory to call my InMemoryCache Class:
public class CacheFactory
{
public static ICache Cache { get; set; }
public static void Insert<T>(string cacheKey, T value)
{
Cache.Insert<T>(cacheKey, value);
}
public static T Get<T>(string cacheKey)
{
return Cache.Get<T>(cacheKey);
}
public static bool Exists<T>(string cacheKey)
{
return Cache.Get<T>(cacheKey) != null;
}
}
I tried Mock Object like below and unable to get the result.
[Fact()]
public void CacheManager_Insert_Test()
{
string cacheKey = "GradeList";
Mock<ICache> mockObject = new Mock<ICache>();
List<Grade> grades = new List<Grade>
{
new Grade() {Id = 1, Name = "A*"},
new Grade() {Id = 2, Name = "A"},
new Grade() {Id = 3, Name = "B"},
new Grade() {Id = 4, Name = "C"},
new Grade() {Id = 5, Name = "D"},
new Grade() {Id = 6, Name = "E"}
};
var mockedObjectCache = new Mock<ICache>();
// Setup mock's Set method
mockedObjectCache.Setup(m => m.Insert(cacheKey, grades));
// How to get the Mocked data and verify it here
}
Could someone check that my data insertion to cache is correct? Also how can I verify the cache data in unit test Moq? I am new to unit testing.
I am not able to verify since I am inserting data to object cache in my implementation class but mocking the interface. I suppose if I could relate both, It might be verifying. Not sure, it's just my guess.
Updated Scenario
Consider having another class named "Convertor" which retrieves the Grade name based on the Grade ID from cache.
public class Convertor
{
// Gets Grade ID and Displays Grade Name
public string GetGradeName(int gradeId)
{
var gradeList = CacheFactory.Cache.Get<List<Grade>>(CacheKeys.Grades);
return gradeList.Where(x => x.Id == gradeId).Select(x => x.Name).FirstOrDefault();
}
}
For this case, how can I verify this? Since this method is using cache to retrieve value, I am not sure how to use mock here.