2014-03-14 3 views
1

비동기 적으로 실행되는 개발 한 라이브러리에 라이브러리 함수가 있습니다. 예 하여 설명 : FUNC1 즉시 라이브러리의 일부의 처리를 개시하고유닛 비동기 메서드 테스트 .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); 
} 

반환.

결과는 처리이다 대리자

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. 그것이 작동하는 지 의심 스럽습니다. Test Method에서 Test() 메서드는 "Func1Async가 완료되면 나머지 메서드가 실행됩니다."- 그러나 라이브러리의 프로세스가 아직 완료되지 않았습니다. (Func1Async가 즉시 반환하고 myLib도 반환합니다. Func1) – user3418770

+0

'Func1Async'는 즉시 반환하지만 'Task'를 반환합니다. 일단 작업이 완료되면 나머지 메소드가 실행됩니다. 이 게시물을보십시오 http://stackoverflow.com/questions/15736736/how-does-await-async-work –

관련 문제