How to mock a class that implements multiple interfaces

前端 未结 4 780
误落风尘
误落风尘 2020-12-05 17:19

How to mock the following class:

UserRepository : GenericRepository, IUserRepository


public class GenericRepository : IGenericRe         


        
4条回答
  •  渐次进展
    2020-12-05 17:52

    If I understand the question correctly, you want have a single mock instance of UserRepository, and for the purposes of a test, setup calls to methods from both the IGenericRepository interface and the IUserRepository interface.

    You can implement multiple interfaces with a single mock instance like this:

    var genericRepositoryMock = new Mock>();
    genericRepositoryMock.Setup(m => m.CallGenericRepositoryMethod()).Returns(false);
    
    var userRepositoryMock = genericRepositoryMock.As();
    userRepositoryMock.Setup(m => m.CallUserRepositoryMethod()).Returns(true);
    

    However, as D Stanley pointed out, the need to do this is probably an indication that there is a flaw in your design.

提交回复
热议问题