c# - 为什么单元测试中未处理的异常不会导致使用 M​​STest 失败?

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

最佳答案

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

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

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

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

关于c# - 为什么单元测试中未处理的异常不会导致使用 M​​STest 失败?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21903711/

相关文章:

java - ComponentScan excludeFilters 在 Spring 4.0.6.RELEASE 中不起作用

xml - 生成 Google C++ 单元测试 XML 报告

c# - 为什么我无法让 Win32_UninterruptiblePowerSupply 工作?

c++ - 如何创建一个空垫子并在其上画线?

C# 图表缩放精度

c# - 从 Sql 检索数据并将其保存为 PDF

unit-testing - 单元测试同步框架

c# - 修剪字符串并将其转换为小写的最快方法

c# - 为什么我的 finally block 在 C# 中不起作用?

c# - 流利的断言 : string does not contain a definition for ShouldBeEquivalentTo