0

In my C# project I am using xUnit and Moq4 for unit testing. The interface that I'm trying to mock looks like this:

public interface IEngine
{
    void Push<T>() where T : IEquatable<T>;
}

I would like to create and setup mock of this interface like this:

[Fact]
public void My_test()
{
   var value = 0;

   var mock = new Mock<IEngine>();

   mock.Setup(m => m.Push<???>()).Callback(() => value++);

   mock.Object.Push<TypeOne>();
   mock.Object.Push<TypeTwo>();

   Assert.Equal(2, value);
}

where TypeOne and TypeTwo are:

public class TypeOne : IEquatable<TypeOne>
{
    public bool Equals(TypeOne? other) => true;
}

public class TypeTwo : IEquatable<TypeTwo>
{
    public bool Equals(TypeTwo? other) => true;
}

What should I write instead of '???' to make my test compile and work? Is it event possible?

I've tried something like

mock.Setup(m => m.Push<IEquatable<It.IsAnyType>>()).Callback(() => value++);

But this doesn't compile with error:

The type 'System.Equatable<Moq.It.IsAnyType>' cannot be used as type parameter 'T' in the generic type or method 'IEngine.Push<T>()'. There is no implicit reference conversion from 'System.Equatable<Moq.It.IsAnyType>' to 'System.Equatable<System.Equatable<Moq.It.IsAnyType>>'.

I've read about ITypeMatcher interface and TypeMatcherAttribute from Moq4. But I can't figure out how to apply it in my case.

Please help.

Dka8
  • 1
  • 1
  • 1
    Doing this should make it compile and work `mock.Setup(m => m.Push()).Callback(() => value++);` and `mock.Setup(m => m.Push()).Callback(() => value++);` – Selmir Aljic Feb 13 '23 at 04:03
  • Yes, this will definitely work. But I was hoping to find a more general approach. One call to setup that will work for any type inherited from `IEquatable` – Dka8 Feb 13 '23 at 12:35
  • There's a similar question asked before on stackoverflow [see here](https://stackoverflow.com/questions/5311023/mocking-generic-method-call-for-any-given-type-parameter) which I think contains information to achieve what you are trying to do. – Selmir Aljic Feb 13 '23 at 14:44

0 Answers0