为什么单元测试中的未处理异常不能使其使用MSTest失败?

Ign*_*cia 2 c# unit-testing mstest exception visual-studio-2010

今天我们意识到有些测试会抛出异常,但所有测试都会"通过".实际上,异常文本以绿色显示.

这有意义吗?

有没有办法让测试失败,如果未处理异常(我知道大部分时间都会发生)?

截图:

在此输入图像描述

测试方法:

[TestMethod]
public void CommunicationCore_CommunicationController_ConnectRequestWellProcessed()
{
    // Arrange
    IUnityContainer container = new UnityContainer();
    ICommonInitializer initializer = new CommonInitializer(container);
    initializer.Initialize(); // register all types
    DriveConnection connectionSettings = CreateFakeConnetionSettings(1);

    Transaction transaction = null;
    ICommunicationController controller = container.Resolve<ICommunicationController>();

    object locker = new object();

    // Act
    controller.Connect(
        connectionSettings,
        result =>
            {
                transaction = result;
                lock (locker)
                {
                    Monitor.Pulse(locker);
                }
        });

    // asyncronous communication wait for the process of the message
    lock (locker)
    {
        Monitor.Wait(locker, 10000);
    }

    // Assert
    bool connectSuccessfully = (transaction != null) && !transaction.Response.ErrorResult.ErrorDetected;
    Assert.IsTrue(connectSuccessfully);

    ((IDisposable)controller).Dispose();
}
Run Code Online (Sandbox Code Playgroud)

hel*_*elb 6

从您发布的调用堆栈中,我看到异常发生在单独的线程中.

似乎只有在测试方法的调用线程中抛出的异常才会导致测试失败.考虑这个例子:

[TestMethod]
public void ThreadExceptionTest()
{
    new Thread(() => { throw new Exception("Error in thread"); }).Start();
}
Run Code Online (Sandbox Code Playgroud)

另请参阅此问题:如何处理异常 - 在其他线程中引发的单元测试