How to Debug Classes Quickly with UiAutomator on Mac OS

Posted by neuromancer on Tue, 01 Oct 2019 07:50:38 +0200

Recently, when I used UiAutomator to debug classes quickly on Mac OS, I found that it is very different from using classes in Windows environment. There are many pits to fill in for my Mac OS white. Today, I finally revised them and shared the code for your reference. The main difference is that when you execute a command, you need to precede it with a full path to execute it. Another problem is the slash bar, which can be changed uniformly.

Errors encountered:

The following is the error message when the full path is not configured:

Cannot run program "android": error=2, No such file or directory Here is the error message when the path error occurs:

Cannot run program "/Users/dahaohaozai/android-sdk-macosx/toos/android": error=2, No such file or directory Here is the code for the debugging class:

package source;
 
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
 
/**
 * @author ··-·dust
 * @E-mail:Fhaohaizi@163.com
 * @version Date of creation: 10:53:24 a.m. on August 18, 2017
 * @alter Modification time: October 23, 2017 10:19:34 Category Notes: Test and Debugging Use Cases
 */
public class UiAutomatorHelper extends Common {
 
	private static String android_id = "1";// Android Id, write well without reference
	private static String jar_name = "";// jar name
	private static String test_class = "";// Package name. Class name
	private static String test_name = "";// Use case name
	// private static String devices = Common.NEXUS5DEVICESID; //Custom device ID
	private static String workspace_path;// The workspace does not need to be configured to automatically get the workspace directory
 
	public UiAutomatorHelper() {// If a class has a parametric construction method, it must write out the hidden empty parameter construction method.
		output("Welcome to use custom debugging classes!");
	}
 
	/**
	 * Construction method
	 * 
	 * @param jarName
	 *            jar Name of package
	 * @param testClass
	 *            Class name
	 * @param testName
	 *            Method name
	 */
	public UiAutomatorHelper(String jarName, String testClass, String testName) {
		output("Welcome to use custom debugging classes!");
		workspace_path = getWorkSpase();
		jar_name = jarName;
		test_class = testClass;
		test_name = testName;
		// Common.getInstance().setMobileInputMethodToUtf(); // Set the input method to utf7
		runUiautomator();
		// Common.getInstance().setMobileInputMethodToQQ(); // Set the input method to QQ input method
		output(Common.LINE + "---FINISH DEBUG----" + Common.LINE);// End
	}
 
	// Operation steps
	private void runUiautomator() {
		creatBuildXml();
		modfileBuild();
		buildWithAnt();
		pushTestJar(workspace_path + "/bin/" + jar_name + ".jar");
		runTest(jar_name, test_class + "#" + test_name);
	}
 
	// Create build.xml
	public void creatBuildXml() {
		// System.out.println"android create uitest-project -n " + jar_name + " -t " +
		// android_id + " -p " + workspace_path);
		execCmd(ANDROID_PATH + "android create uitest-project -n " + jar_name + " -t " + android_id + " -p "
				+ workspace_path);
	}
 
	// Modify build
	public void modfileBuild() {
		StringBuffer stringBuffer = new StringBuffer();// Create and instantiate stringbuffer
		try {
			File file = new File("build.xml");
			if (file.isFile() && file.exists()) { // Determine whether a file exists
				InputStreamReader read = new InputStreamReader(new FileInputStream(file));// Create and instantiate the output character stream (stream conversion) through the file byte input stream
				BufferedReader bufferedReader = new BufferedReader(read);// Create and instantiate BufferedReader to receive character streams
				String lineTxt = null;// Used to receive readline results
				while ((lineTxt = bufferedReader.readLine()) != null) {// Loop Read Processing Content
					if (lineTxt.matches(".*help.*")) {// Regular matching
						lineTxt = lineTxt.replaceAll("help", "build");// Replace help with build
					}
					stringBuffer = stringBuffer.append(lineTxt + "\t\n");// stringbuffer receives modified content
				}
				bufferedReader.close();// Close the flow, depend on it, so close first
				read.close();// Closed flow
			} else {
				System.out.println("The specified file could not be found");
			}
		} catch (Exception e) {
			System.out.println("Error reading file contents");
			e.printStackTrace();
		}
		// Write it back after revision
		writerText("build.xml", new String(stringBuffer));
	}
 
	// ant performs build
	public void buildWithAnt() {
		execCmd(ANT_PATH + "ant");
	}
 
	/**
	 *  jar package push to mobile phone.
	 * @param localPath jar Absolute Path of Packet
	 */
	public void pushTestJar(String localPath) {
		String pushCmd = ADB_PATH + "adb push " + localPath + " /data/local/tmp/";
		execCmd(pushCmd);
	}
 
	/**
	 * Running Use Case Method
	 * 
	 * @param jarName
	 *            jar Package name
	 * @param testName
	 *            Running method name
	 */
	public void runTest(String jarName, String testName) {
		String runCmd = ADB_PATH + "adb shell uiautomator runtest ";
		String testCmd = jarName + ".jar " + "--nohup -c " + testName;
		execCmd(runCmd + testCmd);
	}
 
	// Getting workspace
	public String getWorkSpase() {
		File directory = new File("");// Create and instantiate file objects
		String abPath = directory.getAbsolutePath();// Get the absolute path
		return abPath;
	}
 
	// Execute the cmd command
	public void execCmd(String cmd) {
		try {
			Process p = Runtime.getRuntime().exec(cmd);// Executing cmd commands through runtime classes
			// Correct Output Flow
			InputStream input = p.getInputStream();// Create and instantiate the input byte stream
			BufferedReader reader = new BufferedReader(new InputStreamReader(input));// First, flow transformation is done through inputstreamreader, and then bufferedreader is instantiated to receive content.
			String line = "";
			while ((line = reader.readLine()) != null) {// Cyclic reading
				System.out.println(line);// output
				saveToFile(line, "runlog.log", false);// Save, false means uncovered
			}
			reader.close();// Here reader depends on input and should be turned off first
			input.close();
			// Error Output Stream
			InputStream errorInput = p.getErrorStream();// Create and instantiate the input byte stream
			BufferedReader errorReader = new BufferedReader(new InputStreamReader(errorInput));// First, flow transformation is done through inputstreamreader, and then bufferedreader is instantiated to receive content.
			String eline = "";
			while ((eline = errorReader.readLine()) != null) {// Cyclic reading
				System.out.println(eline);// output
				saveToFile(eline, "runlog.log", false);// Save, false means uncovered
			}
			errorReader.close();// There is a dependency here, so close errorReader first
			errorInput.close();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
	// Overwrite Write File
	public void writerText(String path, String content) {
		File dirFile = new File(path);
		if (!dirFile.exists()) {// If it does not exist, build a new one
			dirFile.mkdir();
		}
		try {
			// Add true here, you can not overwrite the original TXT file content, continue to write
			BufferedWriter bw1 = new BufferedWriter(new FileWriter(path));// Receiving and writing with bufferedwrite through file output stream
			bw1.write(content);// Write content to a file
			bw1.flush();// Forced Output Buffer Content
			bw1.close();// Closed flow
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
 
	// Write to the document. For comments, see the writerText method
	public void saveToFile(String text, String path, boolean isClose) {
		File file = new File("runlog.log");
		BufferedWriter bf = null;
		try {
			FileOutputStream outputStream = new FileOutputStream(file, true);
			OutputStreamWriter outWriter = new OutputStreamWriter(outputStream);
			bf = new BufferedWriter(outWriter);
			bf.append(text);// Add content
			bf.newLine();
			bf.flush();
			if (isClose) {
				bf.close();
			}
		} catch (FileNotFoundException e1) {
			e1.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
 
	}
}

Selection of previous articles

  1. One line of java code prints a heart
  2. Linux performance monitoring software netdata Chinese version
  3. Interface Test Code Coverage (jacoco) Scheme Sharing
  4. Performance testing framework
  5. How to Enjoy Performance Testing on Linux Command Line Interface
  6. Graphic HTTP Brain Map
  7. Writing to everyone about programming thinking
  8. json data formatting output to console
  9. How to Test Probabilistic Business Interface
  10. Automatically convert swagger documents into test code
  11. Mac+httpclient High Concurrency Configuration Example
  12. httpclient handles multi-user simultaneous online

Public Number Map ☢️ Together ~FunTester

Topics: Programming Java Android Mac xml