使用 Xamarin UiTest 启用/禁用 wifi



我尝试在我的Xamarin Ui Test中以编程方式启用/禁用wifi.
我已经找到了这个:Android:如何以编程方式启用/禁用Wifi或互联网连接。但它似乎在 UiTest 中不起作用。

我也尝试了这样的事情:

Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(Context.WifiService);
bool status = false;
wifiManager.SetWifiEnabled(status);

第一行(Android.App.Application.Context)抛出异常:

Message: System.IO.FileNotFoundException : Could not load file or assembly 'Java.Interop, Version=0.1.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065' or one of its dependencies. The system cannot find the file specified.

我正在使用以下命名空间:

using Android.Net.Wifi;
using Android.Content;

我的项目引用了Mono.Android

后门方法对我来说效果很好。

对我有用的解决方案是以下组合:

  • 安卓:如何以编程方式启用/禁用 Wifi 或互联网连接
  • https://learn.microsoft.com/en-us/appcenter/test-cloud/uitest/working-with-backdoors
  • 一些小的自己的更改(用于应用程序上下文/上下文)。只是上下文对我不起作用。

1.:将以下行添加到 Android 项目的 AndroidManifest.xml 文件中:

<uses-permission android:name="android.permission.CHANGE_WIFI_STATE"/>

2.:在 Android 项目的 MainActivity.cs 中添加以下行:

using Java.Interop;
using Android.Net.Wifi;
[Export("ChangeWifiState")]
public void ChangeWifiState(bool state)
{
Context appContext = Android.App.Application.Context;
var wifiManager = (WifiManager)appContext.GetSystemService(WifiService);
wifiManager.SetWifiEnabled(state);
}

3.:从 Xamarin Ui 测试中调用以下方法:

app.Invoke("ChangeWifiState", false);    // true to enable wifi, false to disable wifi

PS:我使用Xamarin Forms。我有四个不同的项目:一个核心项目,一个Android项目,一个UI项目和一个测试项目。

我刚刚找到了第二个解决方案,而无需使用实际的应用程序.它使用 ADB 命令来启用/禁用 wifi:

var process = new System.Diagnostics.Process();
var startInfo = new System.Diagnostics.ProcessStartInfo
{
WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
FileName = "cmd.exe",
Arguments = "/C adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings adb shell input keyevent 19 & adb shell input keyevent 19 & adb shell input keyevent 23 & adb shell input keyevent 82 & adb shell input tap 500 1000"
};
process.StartInfo = startInfo;
process.Start();

这可以在没有根设备:)的情况下使用。
步骤说明:
adb shell am start -a android.intent.action.MAIN -n com.android.settings/.wifi.WifiSettings打开无线网络设置。
adb shell input keyevent 23启用/禁用无线网络。
我不确定为什么使用命令adb shell input keyevent 19,但它有效。
adb shell input keyevent 82单击菜单按钮以变回原始应用程序。
adb shell input tap 500 1000单击坐标 x=500, y=1000(屏幕中心)。对于不同的解决方案,这可能需要更改。
此解决方案的来源:

  • 如何通过亚行关闭无线网络?
  • 亚行外壳输入事件
  • 运行命令提示符命令