单元测试Microsoft Band

本文关键字:Band Microsoft 单元测试 | 更新日期: 2023-09-27 18:24:45

尝试在VS2015中使用MSTest和Microsoft Band nuGet包进行单元测试,并遇到以下错误

"Microsoft.Band.BandIOException: An error occurred while attempting to acquire the Bluetooth device service.
This error can occur if the paired device is unreachable or has become unpaired from the current host. 
System.InvalidOperationException: A method was called at an unexpected time. (Exception from HRESULT: 0x8000000E)".

代码在应用程序内部运行时运行良好。在线路上调用BandClientManager.Instance.ConnectAsync失败。

单元测试Microsoft Band

这里的异常和错误消息没有帮助,但您必须在UI线程上建立蓝牙连接。这是因为应用程序可能会提示用户,询问他们是否允许访问蓝牙设备。

例如,在UWP应用程序中,您可以执行以下操作来确保UI线程的执行:

await Windows.ApplicationModel.Core.CoreApplication.MainView.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
    IBandClient client = await BandClientManager.Instance.ConnectAsync(...);
    ...
});

或者,如果您有权访问UI控件,则可以直接使用其Dispatcher

任何最终调用BluetoothLEDevice.FromBluetoothAddressAsync的代码都必须在UI线程上执行。只要应用程序包清单(.appxmanifest)发生更改,就会出现蓝牙访问提示。

我无法想象这个修复对于单元测试是可靠的,因为没有UI。除了嘲笑客户端接口和完全避免蓝牙之外,我不确定想要的解决方案是什么。