注意
本指南說明如何將 Android NUnit 測試專案自動化,而不是 Xamarin.UITest 專案。 您可以在這裡找到 Xamarin.UITest 資訊。
當您在 Visual Studio 中建立單元測試應用程式 (Android) 專案時(或 Visual Studio for Mac 中的 Android 單元測試專案),此項目預設不會自動執行您的測試。 若要在目標裝置上執行 NUnit 測試,您可以使用下列命令來建立 Android.App.Instrumentation 子類別:
adb shell am instrument
下列步驟說明此程式:
建立名為 TestInstrumentation.cs 的新檔案:
using System; using System.Reflection; using Android.App; using Android.Content; using Android.Runtime; using Xamarin.Android.NUnitLite; namespace App.Tests { [Instrumentation(Name="app.tests.TestInstrumentation")] public class TestInstrumentation : TestSuiteInstrumentation { public TestInstrumentation (IntPtr handle, JniHandleOwnership transfer) : base (handle, transfer) { } protected override void AddTests () { AddTest (Assembly.GetExecutingAssembly ()); } } }
在這裡檔案中,
Xamarin.Android.NUnitLite.TestSuiteInstrumentation
(從 Xamarin.Android.NUnitLite.dll) 會子類別化以建立TestInstrumentation
。實作建
TestInstrumentation
構函式和AddTests
方法。 方法AddTests
會控制實際執行的測試。修改檔案
.csproj
以新增 TestInstrumentation.cs。 例如:<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> ... <ItemGroup> <Compile Include="TestInstrumentation.cs" /> </ItemGroup> <Target Name="RunTests" DependsOnTargets="_ValidateAndroidPackageProperties"> <Exec Command=""$(_AndroidPlatformToolsDirectory)adb" $(AdbTarget) $(AdbOptions) shell am instrument -w $(_AndroidPackage)/app.tests.TestInstrumentation" /> </Target> ... </Project>
以偵錯或發行模式部署您的應用程式,然後停止它。
使用下列命令來執行單元測試。
PACKAGE_NAME
取代為應用程式的套件名稱(套件名稱可在位於 AndroidManifest.xml 的應用程式/manifest/@package
屬性中找到):adb shell am instrument -w PACKAGE_NAME/app.tests.TestInstrumentation
您可以選擇性地修改
.csproj
檔案以新增RunTests
MSBuild 目標。 這可讓您使用類似下列命令叫用單元測試:msbuild /t:RunTests Project.csproj
(請注意,不需要使用此新目標;可以使用先前的
adb
命令,而不是msbuild
。
如需使用 adb shell am instrument
命令執行單元測試的詳細資訊,請參閱使用ADB執行Android開發人員測試主題。
注意
使用 Xamarin.Android 5.0 版本,Android 可呼叫包裝函式的預設套件名稱將會以所匯出類型之元件限定名稱的 MD5SUM 為基礎。 這可讓從兩個不同的元件提供相同的完整名稱,而不會收到封裝錯誤。 因此,請務必使用 Name
屬性上的 Instrumentation
屬性來產生可讀取的 ACW/類別名稱。
ACW 名稱必須用於 adb
上述命令中。
因此,重新命名/重構 C# 類別需要修改 RunTests
命令,才能使用正確的 ACW 名稱。