Here is a working example of CacheService
stub:
cacheService
.Stub(s => s.Get(Arg<string>.Is.Anything, Arg<Func<SomeDto>>.Is.Anything))
.WhenCalled(m =>
{
var func = (Func<SomeDto>)m.Arguments[1];
m.ReturnValue = func();
})
.Return(null);
You was getting null
because m.ReturnValue
wasn't set. So default was used a a value to return.
Return()
argument is ignored in case of WhenCalled()
usage - and this is confusing very often.
Here is also a bit different solution:
I personally prefere to use Do()
handler rather than WhenCaled()
in similar cases. It allows to write the stub handler in a type safe way:
cacheService
.Stub(s => s.Get(Arg<string>.Is.Anything, Arg<Func<SomeDto>>.Is.Anything))
.Do((Func<string, Func<SomeDto>, SomeDto>)((key, funcWhenNotExist) =>
{
return funcWhenNotExist();
}));
Please note Return(null)
isn't necessary here anymore. The only thing you need to do is to explicitly convert lambda to stubbed method signature.
Hope that helps.