Mocking generics that implement multiple interfaces

前端 未结 2 1440
北恋
北恋 2021-01-18 19:05

Here\'s my class implementation where the generic is implementing two interfaces...

public class ClassA : where TGeneric: IInterfaceA, IInter         


        
相关标签:
2条回答
  • 2021-01-18 19:19

    As alternative to the accepted answer you can achieve what you need by casting the mocked object to dynamic and at runtime it will work as expected.

    void Main()
    {
        var mockA = new Mock<IIntA>();
        mockA.Setup(a => a.DoA()).Returns(3);
    
        var mockB = mockA.As<IIntB>();
        mockB.Setup(iib => iib.DoB()).Returns(7);
    
        dynamic d = mockB.Object;
    
        TakeBoth(d);
    }
    
    void TakeBoth<T>(T obj) where T : IIntA, IIntB
    {
    }
    
    public interface IIntA { int DoA(); }
    public interface IIntB { int DoB(); }
    
    0 讨论(0)
  • 2021-01-18 19:23

    You could define an interface that includes both interface A and B (in your test project, for testing purposes), then use that in your mock.

    public interface ICanTestAAndB : IInterfaceA, IInterfaceB {}
    
    var mock = new Mock<ClassA<ICanTestAAndB>>();
    
    0 讨论(0)
提交回复
热议问题