【问题标题】:Why an unhandled exception on a unittest does not make it fail using MSTest?为什么单元测试上未处理的异常不会使其使用 MSTest 失败?
【发布时间】:2014-02-20 09:36:31
【问题描述】:

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

这有意义吗?

如果异常未处理,有没有办法使测试失败(我知道大多数情况下都会发生这种情况)?

截图:

测试方法:

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

【问题讨论】:

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


【解决方案1】:

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

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-03-19
    • 1970-01-01
    • 2012-07-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多