2014-03-14 54 views
1

我在开发的库中有异步执行的库函数。 说明通过示例:异步方法的单元测试.NET 4.0风格

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

因此,这里的问题: 我如何写这个单元测试?

+2

我建议你检查这个http://stackoverflow.com/questions/15207631/how-to-write-unit-test-cases-for-async-methods –

回答

1

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

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

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... 
    } 
+0

谢谢,现在固定尽管 –

+0

罚款的做法,我有几个问题无线它:1.这不是我问的。 2.我怀疑它是否有效:在测试方法aka Test()中,“Func1Async完成时执行其余的方法” - 但库中的进程尚未完成...(Func1Async立即返回,myLib也会立即返回。 Func1) – user3418770

+0

'Func1Async'立即返回,但它返回一个'Task',一旦任务完成,方法的其余部分被执行。看看这篇文章http://stackoverflow.com/questions/15736736/how-does-await-async-work –