Search code examples
c#unit-testingmockingmoqazure-redis-cache

Moq Returns method not working as expected


Take a look at this code:

var thirdLevelCacheMock = new Mock<IDatabase>();
RedisValue val = "not empty or null string";
thirdLevelCacheMock.Setup(m => m.StringGetAsync(It.IsAny<string>(), It.IsAny<CommandFlags>())).Returns(Task.FromResult(val));

CachingInfrastructure caching = new CachingInfrastructure();
caching._thirdLevelCache = thirdLevelCacheMock.Object;

var operation = caching.GetKeyAsync("bla", CacheLevel.Any);

Assert.DoesNotThrow(() => { operation.Wait(); });
Assert.IsNotNull(operation.Result);

As you can notice, i'm setting the return of StringGetAsync to a simple not empty/null string.

My problem is that, inside the caching.GetKeyAsync, the call to that method, is returning a null result. What am I doing wrong here?

Code for GetKeyAsync:

result = _thirdLevelCache.StringGetAsync(key, CommandFlags.None).ContinueWith((prev) =>
      {
            string res = null;
            if (!prev.Result.IsNull)
            {
               res = prev.Result.ToString();
            }
            return res as object;
      });

Solution

  • I replaced It.IsAny<string>() by It.IsAny<RedisKey>()