PSR
PSR

Reputation: 893

How to mock generic method with delegate parameter

In a abstract class I have a virtual method with this signature.

public virtual async Task<TResult> MethodAsync<TParameters, TResult>(
        CommandFactory<TParameters> commandFactory,
        TParameters parameters,
        ModelAdapter<TResult> modelAdapter)
    { // method body }

CommandFactory and ModelAdapter are delegates with this signature.

public delegate DbCommand CommandFactory<in TParameters>(
    DbConnection connection,
    TParameters parameters);

public delegate TResult ModelAdapter<out TResult>(DbDataReader dataReader);

How to mock MethodAsync using Moq

Upvotes: 1

Views: 186

Answers (1)

Nkosi
Nkosi

Reputation: 247561

It can be setup like any other virtual or abstract member

var mock = new Mock<MyAbstractClass>();
string expectedResult = "Hello World";
mock
    .Setup(_ => 
        _.MethodAsync(
            It.IsAny<CommandFactory<string>>(),
            It.IsAny<string>(),
            It.IsAny<ModelAdapter<string>>())
        )
    .ReturnsAsync(expectedResult);

The above example is simplifies to use strings just to demonstrate how the generic parameters are used.

It.IsAny argument matcher was used to setup the expectations for the parameters of the method

Upvotes: 1

Related Questions