简体   繁体   English

用Moq模拟异步静态方法

[英]Mock async static method with Moq

so far I have been able to mock static methods by changing its signature to something like (pseudo) 到目前为止,我已经能够通过将其签名更改为类似(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? 现在嘲笑此委托人的正确方法应该是什么?

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, ie 注意:不确定您的TResult来自哪里,但是由于不可能在C#中具有泛型函数的实例,因此在编写模拟时,您的TResult必须为“已知”,即

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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM