Goran Sneperger
Goran Sneperger

Reputation: 87

Mock async static method with Moq

so far I have been able to mock static methods by changing its signature to something like (pseudo)

public static Func<TResult> Foo = () => { return TResult; };

Then in test I could mock it via

MyClass.Foo = () => new TResult();

I am facing a new problem now.

There is a method with a signature something like:

public static async Task<TResult> FooBar(string obj1, string obj2)

I have changed it to

public static Func<string, string, Task<TResult>> FooBar = async (obj1, obj2)

and this compiles nicely, but I don't get it to compile for the test.

MyClass.FooBar(It.IsAny<string>(), It.IsAny<string>()) => Task.FromResult(new TResult());

I know I should have await placed somewhere in the whole call but it just won't budge. What should be the proper way of mocking this delegate now?

Upvotes: 2

Views: 858

Answers (1)

Vladi Pavelka
Vladi Pavelka

Reputation: 926

Would this work for you?

MyClass.FooBar = (string obj1, string obj2) => Task.FromResult(new TResult());

Note: not sure where your TResult is comming from, but as it is not possible to have instances of generic functions in C#, your TResult must be "known" at the time of writing the mock, i.e.

public static Func<string, string, Task<int>> Foo = Bar<int>;            
public static async Task<TResult> Bar<TResult>(string obj1, string obj2) where TResult : new()
    => await Task.FromResult(new TResult());

Upvotes: 2

Related Questions