Mocking generic method call for any given type parameter

后端 未结 4 1806
孤独总比滥情好
孤独总比滥情好 2020-12-05 12:35

I have an interface

public interface IDataProvider
{
    T GetDataDocument(Guid document) where T:class, new()
}

I\'d like to mock

4条回答
  •  再見小時候
    2020-12-05 13:22

    I had a similar issue, I chose against using a stub in this situation as I did not want additions to the interface being tested to require immediate changes to the test code. i.e. adding a new method should not break my existing tests.

    To get the mock working I added all the public type in a given assembly at runtime.

    //This is fairly expensive so cache the types
    static DummyRepository()
    {
        foreach( var type in typeof( SomeTypeInAssemblyWithModelObjects ).Assembly.GetTypes() )
        {
            if( !type.IsClass | type.IsAbstract || !type.IsPublic || type.IsGenericTypeDefinition )
            {
                continue;
            }
    
            g_types.Add( type );
        }
    }
    
    public DummyRepository()
    {
        MockRepository = new Mock();
    
        var setupLoadBy = GetType().GetMethod( "SetupLoadBy", BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.InvokeMethod );
    
        foreach( var type in g_types )
        {
            var loadMethod = setupLoadBy.MakeGenericMethod( type );
            loadMethod.Invoke( this, null );
        }
    }
    
    private void SetupLoadBy()
    {
        MockRepository.Setup( u => u.Load( It.IsAny() ) ).Returns( LoadById );
    }
    
    public T LoadById( long id )
    {
    }
    

提交回复
热议问题