0
votes

I've found loads of questions to the error message, but not one that matches my specific case.

I have a method with this signature in a cache implementation:

public bool TryGet(TKey key, out TValue returnVal, Func<TKey, TValue> externalFunc = null)

I have a class derived from that with TKey : CompositeKey and TValue : string.

I'm trying to mock it for unit testing like this:

_cacheMock
    .Setup(x => x.TryGet(It.IsAny<CompositeKey>(), out It.Ref<string>.IsAny, It.IsAny<Func<CompositeKey, string>>()))
    .Returns((CompositeKey key, out string s, Func<CompositeKey, string> fetchOne) => { s = ""; return true; });

I get a compilation error for the .Returns line:

"Cannot convert lambda expression to type 'bool' because it is not a delegate type"

If I remove the "out" modifier it compiles OK - but of course doesn't match the signature of the call and I can't get the out value out.

Is there a way to fix the Returns() part of the statement without modifying the TryGet() method itself?

1

1 Answers

1
votes

This might work for you:

//define the callback delegate
delegate void TryGetCallback(CompositeKey key, out string str, Func<CompositeKey, string> func);

mock.Setup(x => x.TryGet(
        It.IsAny<CompositeKey>(), 
        out It.Ref<string>.IsAny, 
        It.IsAny<Func<CompositeKey, string>>()))
    .Callback(new TryGetCallback((CompositeKey key, out string str, Func<CompositeKey, string>  func) => 
    { 
        str = "foo bar"; 
    }))
    .Returns(true);

with such a setup you could archive what you want

string actualValue;
bool result = mock.Object.TryGet(new CompositeKey(), out actualValue)
//actualValue = "foo bar", result = true