【发布时间】: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