【问题标题】:Why does my MSTest project only catch this exception when "Debug"d and not "Run"d?为什么我的 MSTest 项目仅在“Debug”d 而不是“Run”d 时捕获此异常?
【发布时间】:2019-07-20 13:58:31
【问题描述】:

我正在使用 MSTest 围绕 Windows 10 蓝牙低功耗 API 编写一些 TDD 风格的代码。当扫描期间发现 BLE 外设时,我有一个由操作系统调用的回调。

void StartScan()
{
    _BleWatcher = new BluetoothLEAdvertisementWatcher();
    _BleWatcher.Received += ScanDiscovery;
    _BleWatcher.Start();
}

// this usually fires in under a second, and always in under ten seconds
void ScanDiscovery(BluetoothLEAdvertisementWatcher watcher, BluetoothLEAdvertisementReceivedEventArgs bleAdvert)
{
    Debug.WriteLine("This handler was indeed called.");
    throw new Exception();
}

如果我“运行选定的测试”并且在回调中发生异常,则运行进程显然没有检测到它。测试通过,异常不会阻止被测单元正常运行。

[TestMethod]
async Task ScanTest()
{
    StartScan();
    await Task.Delay(10000);
    // this always completes, even though I see the debug message in the Output
}

但是,如果我“调试选定的测试”,Visual Studio 会按预期提醒我异常!

对于像BluetoothLEAdvertisementWatcher.Received 这样的 Windows API 如何确定进程如何路由和捕获异常,是否存在“不同”?

该项目面向 .NET Standard 2.0,使用 this trick 访问 UWP API。

【问题讨论】:

  • 最大的区别在于 UI 线程。
  • 显然没有用于测试的 UI,但线程结构实际上有何不同?
  • 您能否验证在您的单元测试中实际调用了事件处理程序?
  • 在里面打断点调试单元测试
  • @Dave:已编辑代码以添加我将用于验证调用的输出。我也只是尝试了“调试”而不是“运行”,并且“调试”的行为与应用程序相同。编辑问题以反映更小的情况。谢谢!

标签: c# visual-studio unit-testing uwp mstest


【解决方案1】:

您的线程上没有引发 ScanDiscovery 事件。它由调用 _BleWatcher.Start() 创建的线程引发。由于它与 ScanTest() 不在同一线程上运行,因此您无法在此处捕获异常。

在调试模式下,无论在哪个线程上运行,Visual Studio 都会在抛出异常时停止。

您需要在 ScanDiscovery 中捕获异常或查看 AppDomain.UnhandledException 之类的内容。

【讨论】:

    猜你喜欢
    • 2011-02-13
    • 1970-01-01
    • 1970-01-01
    • 2012-02-05
    • 2013-07-16
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    相关资源
    最近更新 更多