【发布时间】:2011-10-01 01:15:28
【问题描述】:
下面的源代码是关于我的问题的示例代码 sn-p。我希望调用异步操作时会发生异常。
单元测试
[TestMethod()]
[ExpectedException(typeof(Exception))]
public void OperateAsyncTest()
{
//Arrange
var testAsyncClass = new TestAsyncClass();
//Act
testAsyncClass.OperateAsync();
}
代码
public class TestAsyncClass
{
public void OperateAsync()
{
ThreadPool.QueueUserWorkItem( obj =>{
throw new Exception("an exception is occurred.");
});
}
}
但是,MsTest 无法捕获异常,因为可能测试线程与抛出异常的线程不同。 如何解决这个问题?有什么想法吗?
以下代码是我的解决方法,但它既不聪明也不优雅。
解决方法
[TestClass()]
public class TestAsyncClassTest
{
private static Exception _exception = new Exception();
private static readonly EventWaitHandle ExceptionWaitHandle = new AutoResetEvent(false);
static TestAsyncClassTest()
{
AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
}
static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
{
_exception = (Exception)e.ExceptionObject;
ExceptionWaitHandle.Set();
}
[TestMethod()]
[ExpectedException(typeof(Exception))]
public void OperateAsyncTest()
{
//Arrange
var testAsyncClass = new TestAsyncClass();
//Act
lock(_exception)
{
testAsyncClass.OperateAsync();
ExceptionWaitHandle.WaitOne();
throw _exception;
}
}
}
【问题讨论】:
标签: c# unit-testing mstest