Search code examples
c#androidseleniumappium

How to close down Android SDK emulator after running tests


I am using Appium to run automated tests on an android emulator. I cannot seem to close the emulator down after the tests have finished. The research I have done seems to point to _driver.Quit(); closing the emulator but it remains running.

How do I close down the emulator after I have run a test?

Code:

[TestClass]
public class UnitTest
{
    AndroidDriver<AndroidElement> _driver;

    private static Uri testServerAddress = new Uri("http://127.0.01:4723/wd/hub");
    private static TimeSpan INIT_TIMEOUT_SEC = TimeSpan.FromSeconds(180);

    [TestInitialize]
    public void BeforeAll()
    {
        DesiredCapabilities cap = new DesiredCapabilities();

        cap.SetCapability("avd", "Device_01_Oreo_1440x2560");
        cap.SetCapability("deviceName", "Device 01 Oreo_1440x2560");
        cap.SetCapability("platformName", "Android");
        cap.SetCapability("platformVersion", "8.1.0");
        cap.SetCapability("udid", "emulator-5554");
        cap.SetCapability("appPackage", "appPackage");
        cap.SetCapability("appActivity", "appActivity");
        cap.SetCapability("unicodeKeyboard", true);
        cap.SetCapability("resetKeyboard", true);

        _driver = new AndroidDriver<AndroidElement>(testServerAddress, cap, INIT_TIMEOUT_SEC);
    }

    [TestMethod]
    public void Test_Open_Mobile_App()
    {
        _driver.FindElement(MobileBy.XPath("//android.widget.EditText[@index='0' and @password='false']")).SendKeys("EmailAddress");
        _driver.FindElement(MobileBy.XPath("//android.widget.EditText[@index='0' and @password='true']")).SendKeys("Password");
    }

    [TestCleanup]
    public void AfterAll()
    {
        _driver.CloseApp();
        _driver.Quit();
    }
}

Edit:

I have just tried to complete this task by killing the emulator process using the below:

Regex regex = new Regex(@"qemu-system.*");
foreach (Process p in Process.GetProcesses("."))
{
    if (regex.Match(p.ProcessName).Success)
    {
        p.Kill();
    }
}

This closes the android emulator down, however it also closes the Appium server down as well and therefore testing sequential devices wouldn't work.

So if there is a why to kill the emulator without killing the Appium server then this would also help my situation.


Solution

  • Appium does not let you terminate emulator instances. But you can use adb to shut them down. Incorporate something like below into your tear down code.

    string cmdstr;
    cmdstr="adb -s emulator-5554 emu kill"
    System.Diagnostics.Process.Start("CMD.exe",cmdstr);