2010-08-20 4 views
3

Je suis en train de tester le code qui démarre un thread secondaire. Et ce fil jette parfois une exception. Je voudrais écrire un test qui échoue si cette exception n'est pas gérée correctement.Exception de thread secondaire NUnit

J'ai préparé ce test, et ce que je vois dans NUnit est:

LegacyImportWrapperTests.Import_ExceptionInImport_Ok : PassedSystem.ArgumentException: aaaaaaaaaa 
at Import.Legacy.Tests.Stub.ImportStub.Import() in ImportStub.cs: line 51... 

Mais le test est marqué comme GREEN. Donc, NUnit connaît cette exception, mais pourquoi le marque-t-il comme étant Passé?

Répondre

4

Si vous voyez les détails de l'exception dans la sortie, cela ne signifie pas nécessairement que NUnit est conscient de l'exception.

J'ai utilisé le pour suivre des scénarios comme celui-ci lors des tests événement AppDomain.UnhandledException (étant donné que l'exception est non gérée, que je suppose est le cas ici):

bool exceptionWasThrown = false; 
UnhandledExceptionEventHandler unhandledExceptionHandler = (s, e) => 
{ 
    if (!exceptionWasThrown) 
    { 
     exceptionWasThrown = true; 
    } 
}; 

AppDomain.CurrentDomain.UnhandledException += unhandledExceptionHandler; 

// perform the test here, using whatever synchronization mechanisms needed 
// to wait for threads to finish 

// ...and detach the event handler 
AppDomain.CurrentDomain.UnhandledException -= unhandledExceptionHandler; 

// make assertions 
Assert.IsFalse(exceptionWasThrown, "There was at least one unhandled exception"); 

Si vous voulez tester uniquement des exceptions spécifiques vous pouvez le faire dans le gestionnaire d'événements:

UnhandledExceptionEventHandler unhandledExceptionHandler = (s, e) => 
{ 
    if (!exceptionWasThrown) 
    { 
     exceptionWasThrown = e.ExceptionObject.GetType() == 
           typeof(PassedSystem.ArgumentException); 
    } 
}; 
Questions connexes