Strange Moq issue when trying to use Mock <T> for generic type

A bit of code:

public interface IMyInterface { int GetIt(); } public class MyImplementation : IMyInterface { public int GetIt() { return 10; } } [Test] public void Testit() { Method<MyImplementation>(); } private void Method<T>() where T : class , IMyInterface { var mock = new Mock<T>(); mock.Setup(m => m.GetIt()).Returns(() => { return 40; }); Assert.AreEqual(40, mock.Object.GetIt()); } 

Note that when I upgrade Mock, I use a generic T, however, since T is limited to the reference type and IMyInterface type, I can configure the methods without problems. For some reason, however, it always fails and calls the actual implementation of MyImplementation , unlike Mocked.

+4
source share
1 answer

You essentially make fun of a class method, and for this the method must be virtual.

Try

 public class MyImplementation : IMyInterface { public virtual int GetIt() { return 10; } } 
+4
source

All Articles