【问题标题】:How to mock async method which is inside a void method?如何模拟 void 方法中的异步方法?
【发布时间】:2015-12-02 10:25:19
【问题描述】:

我在视图模型中有一个 void 方法

public void TestMethod()
{
    AsyncMethod01();
    AsyncMethod02();
}

在那个 void 方法里面有两个异步方法被调用

async void AsyncMethod01()
{
    ServiceResponse<ObservableCollection<User>> response = await 
        Task.Factory.StartNew<ServiceResponse<ObservableCollection<User>>>(UserDetails);
}

async void AsyncMethod02()
{
    ServiceResponse<ObservableCollection<Customer>> response = await
        Task.Factory.StartNew<ServiceResponse<ObservableCollection<Customer>>>(CustDetails);
}

所以我需要使用 moq 为 TestMethod() 编写一个单元测试

[TestMethod]
public async Task TestMethodForViewModel()
{
    //Code
}

那么如何为 void TestMethod() 编写单元测试,其中包含两个异步方法。所以我需要一种方法来等到单元测试方法中的两个异步调用完成。

【问题讨论】:

    标签: c# unit-testing async-await moq


    【解决方案1】:

    这对你有什么作用?

    [TestMethod]
    public async Task TestMethodForViewModel()
    {
        await AsyncMethod01();
        await AsyncMethod02();
    }
    

    【讨论】:

    • 不能这样使用,因为这两种方法都是私有的。只有 TestMethod() 的访问权限
    • 基本上,任何调用异步方法的东西本身都需要是异步的。将测试方法更改为异步任务。
    • 有什么可能的方法从头开始?
    猜你喜欢
    • 1970-01-01
    • 2015-03-08
    • 1970-01-01
    • 1970-01-01
    • 2021-04-12
    • 1970-01-01
    • 2014-01-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多