0

I have the following interface

public interface Itf {
   bool M();
   bool Method<T>(Expression<Func<T, bool>> x);
}

I cannot figure out how to mock the method Method (using Moq)

var mck = new Mock<Itf>();
mck.Setup(o => o.M()).Callback(() => { }); //Ok
mck.Setup(o => o.Method(???)).Callback(x => {...}); //What should I replace ??? with?

DESIRED BEHAVIOUR

What I would like to achieve is to have my callback called whenever Method is called. This is what I tried :

mck.Setup(o => o.Method(It.IsAny<Expression<Func<DocumentCollectionModel, bool>>>()))).Callback<Expression<Func<DocumentCollectionModel, bool>>>(x => {...}); //OK

mck.Setup(o => o.Method(It.IsAny<Expression<Func<It.IsAnyType, bool>>>()))).Callback<Expression<Func<It.IsAnyType, bool>>>(x => {...}); //Callack not called

mck.Setup(o => o.Method(It.IsAny<Expression<Func<It.IsSubtype<object>, bool>>>()))).Callback<Expression<Func<It.IsSubtype<object>, bool>>>(x => {...}); //Callack not called

While the first example works, if possible I would like to have it generic, like the second or third, otherwise I have to repeat the mock for every specific type.

Franco Tiveron
  • 2,364
  • 18
  • 34
  • See [Mocking generic methods in Moq without specifying T](https://stackoverflow.com/questions/20072429/mocking-generic-methods-in-moq-without-specifying-t). It seems to be similar to your problem. – viktor.hadomskyi Sep 08 '20 at 11:43
  • I've never worked with moq but from a quick read of the [quickstart](https://github.com/Moq/moq4/wiki/Quickstart) - are you looking for `It.IsAny>>()`? – Zohar Peled Sep 08 '20 at 11:45
  • More context is needed about what it is you are actually trying to test. The question in its current state is incomplete and therefore unclear. – Nkosi Sep 08 '20 at 11:50
  • 2
    `What should I replace ??? with?` That depends on what you are actually trying to test. – Nkosi Sep 08 '20 at 11:50

1 Answers1

3

You have to specify your type T in the test method.

Assuming T is string, this should work (in XUnit):

mck.Setup(o => o.Method(It.IsAny<Expression<Func<string, bool>>>()))
    .Callback<Expression<Func<string, bool>>>(x => {...});
Nkosi
  • 235,767
  • 35
  • 427
  • 472
kalu93
  • 226
  • 2
  • 4