Mocking generics that implement multiple interfaces

前端 未结 2 1461
北恋
北恋 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();
        mockA.Setup(a => a.DoA()).Returns(3);
    
        var mockB = mockA.As();
        mockB.Setup(iib => iib.DoB()).Returns(7);
    
        dynamic d = mockB.Object;
    
        TakeBoth(d);
    }
    
    void TakeBoth(T obj) where T : IIntA, IIntB
    {
    }
    
    public interface IIntA { int DoA(); }
    public interface IIntB { int DoB(); }
    

提交回复
热议问题