Detecting app crashes on iOS/ Android using Appium

Abhishek Dhoundiyal
2 min readFeb 26, 2023

--

For iOS Devices:

The code will check if your app is getting code “1” which means that the app has Crashed.

If it will get the app code “1” then it will close the session and stop the test case execution.

mobile: queryAppState

Queries the state of an existing application on the device. There are five possible application states (check Apple’s documentation for more details):

  • 0: The current application state cannot be determined/is unknown
  • 1: The application is not running
  • 2: The application is running in the background and is suspended
  • 3: The application is running in the background and is not suspended
  • 4: The application is running in the foreground

Supported arguments

  • bundleId: The bundle identifier of the application, which state is going to be queried. Mandatory argument.
Map<String, Object> params = new HashMap<>();
params.put("bundleId", "com.yourAppBundleId");
final int state = (Integer)js.executeScript("mobile: queryAppState", params);
try {
JavascriptExecutor js = (JavascriptExecutor) driver;
Map<String, Object> params = new HashMap<>();
params.put("bundleId", "com.yourAppBundleId");
final Long state = (Long)js.executeScript("mobile: queryAppState", params);
log.info("Application state code is :"+state);
if (state==1) {
log.error(LogStatus.FAIL, "Application is Crashed");
driver.close();
driver.quit();
}
}
catch (Exception e){
log.error("Application state error :" +e);
}

For Android Devices:

List<LogEntry> adbLogs = driver().manage().logs().get("logcat").filter(Level.ALL);
log.info("First timestamp: " + adbLogs.get(0).getTimestamp());
log.info("Last timestamp: " + adbLogs.get(adbLogs.size()-1).getTimestamp());

public void getMobileLogs(AppiumDriver driver) {
try {
String formattedDate = new SimpleDateFormat(DATE_FORMAT).format(new Date());
log.info(driver.getSessionId() + ": Saving device log...");
List<LogEntry> logEntries = driver.manage().logs().get("logcat").getAll();
log.debug("--------------------START---------------------------");
for (LogEntry entry : logEntries) {
String debugLevel = entry.getLevel().toString().trim();
String debugMessage = entry.getMessage().trim();
log.debug(formattedDate + LINE_BREAK + debugLevel + LINE_BREAK + debugMessage);
}
log.debug("--------------------END----------------------------");
} catch (Exception ex) {
log.fatal(ex.getMessage());
}
}

Other:

List<LogEntry> adbLogs = driver().manage().logs().get("logcat").filter(Level.ALL);
List<LogEntry> adbLogs = driver().manage().logs().get("crashlog").filter(Level.ALL);

Types as per documentation:

  • logTypes.should.include(‘syslog’);
  • logTypes.should.include(‘crashlog’);
  • logTypes.should.not.include(‘logcat’);

Ref: https://github.com/appium/appium/blob/37afd9842c37598f2180172ba183ff1413ddf4f9/test/functional/ios/testapp/basics/calc-app-2-specs.js#L49

--

--