Search code examples
unit-testinggenericsmockingmicrosoft-fakesstubbing

How to stub out a generic method definition in an interface using Microsoft Fakes in c#


I have a unit test which stubs out the following interface using Microsoft Fakes:

public interface ITable
{
    Task<TableResult> Retrieve(string tableReference, string partitionKey, string rowKey);
}

The stub looks like this:

ITable table = new MessagesAPI.Azure.Fakes.StubITable()
            {
                RetrieveStringStringString = delegate
                  {
                      TableResult tableResult = new TableResult();
                      return Task.FromResult(tableResult);
                  }
            };

This works fine. However I'd like to change the interface to be more generic like so:

public interface ITable
{
    Task<TableResult> Retrieve<T>(string tableReference, string partitionKey, string rowKey) 
                     where T : ITableEntity;
}

Question is how would I stub this new version of the interface out? I'm having trouble getting the syntax right.

Any ideas?


Solution

  • You set the behavior as the following:

    var table = new MessagesAPI.Azure.Fakes.StubITable();
    
    table.RetrieveOf1StringStringString<ITableEntity>(
         (tableReference, partitionKey, rowKey) =>
    {
        TableResult tableResult = new TableResult();
        return Task.FromResult(tableResult);
    });