Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/299.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 异步方法的单元测试.NET4.0风格_C#_Unit Testing_Asynchronous - Fatal编程技术网

C# 异步方法的单元测试.NET4.0风格

C# 异步方法的单元测试.NET4.0风格,c#,unit-testing,asynchronous,C#,Unit Testing,Asynchronous,我开发的库中有异步执行的库函数。 举例说明: private void Init() { // subscribe to method completion event myLib.CompletionEvent += myLib_CompletionEvent; } private void MyButton1_Click(object sender, EventArgs e) { // start execution of Func1 myLib.F

我开发的库中有异步执行的库函数。 举例说明:

private void Init()
{
     // subscribe to method completion event
     myLib.CompletionEvent += myLib_CompletionEvent; 
}

private void MyButton1_Click(object sender, EventArgs e)
{
    // start execution of Func1 
    myLib.Func1(param1, param2);
}
Func1在库中启动一些处理并立即返回

处理的结果通过委托作为事件到达客户机

void myLib_CompletionEvent(ActionResult ar)
{
    // ar object contains all the results: success/failure flag 
    // and error message in the case of failure.
    Debug.Write(String.Format("Success: {0}", ar.success);
}
问题是:
如何为此编写单元测试?

我建议使用创建一个基于任务的异步方法,然后使用对
async\wait的支持,通过测试MsTest和Nunit等框架来编写异步单元测试。测试必须标记为
async
,并且通常需要返回
任务

您可以这样编写异步方法(未经测试):


我建议您检查这个虽然很好的方法,但我有几个问题:1。这不是我所要求的。2.我怀疑它是否有效:在测试方法aka Test()中,“在Func1Async完成后执行方法的其余部分”-但库中的进程尚未完成…(Func1Async立即返回,myLib.Func1也是如此)
Func1Async
立即返回,但它返回一个
任务
,任务完成后,将执行方法的其余部分。看看这个帖子
public Task Func1Async(object param1, object param2)
{
   var tcs = new TaskCompletionSource<object>();

    myLib.CompletionEvent += (r => 
    {
        Debug.Write(String.Format("Success: {0}", ar.success));

        // if failure, get exception from r, which is of type ActionResult and 
        // set the exception on the TaskCompletionSource via tcs.SetException(e)

        // if success set the result
        tcs.SetResult(null);
    });

    // call the asynchronous function, which returns immediately
    myLib.Func1(param1, param2);

    //return the task associated with the TaskCompletionSource
    return tcs.Task;
}
    [TestMethod]
    public async Task Test()
    {
         var param1 = //..
         var param2 = //..

         await Func1Async(param1, param2);

         //The rest of the method gets executed once Func1Async completes

         //Assert on something...
    }