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

时间:2014-02-20 09:36:32

标签: c# visual-studio-2010 unit-testing exception mstest

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

这有意义吗?

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

截图:

enter image description here

测试方法:

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

1 个答案:

答案 0 :(得分:6)

从你发布的调用堆栈中,我看到异常发生在一个单独的线程中。

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

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

另请参阅此问题:how-to-handle-exceptions-raised-in-other-threads-when-unit-testing