Android 응용 프로그램 (Robotium 사용)에 대한 자동 테스트를 개발 중입니다. 테스트의 일관성과 신뢰성을 보장하기 위해 각 테스트를 깨끗한 상태 (테스트중인 응용 프로그램)로 시작하고 싶습니다. 그렇게하려면 앱 데이터를 지워야합니다. 설정 / 응용 프로그램 / 응용 프로그램 관리 / [내 응용 프로그램] / 데이터 지우기에서 수동으로 수행 할 수 있습니다.
프로그래밍 방식으로이 작업을 수행하는 데 권장되는 방법은 무엇입니까?
Android 응용 프로그램 (Robotium 사용)에 대한 자동 테스트를 개발 중입니다. 테스트의 일관성과 신뢰성을 보장하기 위해 각 테스트를 깨끗한 상태 (테스트중인 응용 프로그램)로 시작하고 싶습니다. 그렇게하려면 앱 데이터를 지워야합니다. 설정 / 응용 프로그램 / 응용 프로그램 관리 / [내 응용 프로그램] / 데이터 지우기에서 수동으로 수행 할 수 있습니다.
프로그래밍 방식으로이 작업을 수행하는 데 권장되는 방법은 무엇입니까?
답변:
패키지 관리자 도구를 사용하여 설치된 앱의 데이터를 지울 수 있습니다 (장치의 앱 설정에서 '데이터 지우기'버튼을 누르는 것과 유사). 따라서 adb를 사용하면 다음을 수행 할 수 있습니다.
adb shell pm clear my.wonderful.app.package
Error: unknown command 'clear'.
@edovino의 대답에 따라 프로그래밍 방식으로 모든 응용 프로그램 환경 설정 을 지우는 방법 은 다음과 같습니다.
private void clearPreferences() {
try {
// clearing app data
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear YOUR_APP_PACKAGE_GOES HERE");
} catch (Exception e) {
e.printStackTrace();
}
}
경고 : 응용 프로그램이 강제로 종료됩니다.
이것으로 SharedPreferences 앱 데이터를 지울 수 있습니다.
Editor editor =
context.getSharedPreferences(PREF_FILE_NAME, Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
그리고 app db를 지우려면이 대답은 정확합니다-> Clearing Application database
API 버전 19부터 ActivityManager.clearApplicationUserData ()를 호출 할 수 있습니다.
((ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE)).clearApplicationUserData();
이 코드를 확인하여 다음을 수행하십시오.
@Override
protected void onDestroy() {
// closing Entire Application
android.os.Process.killProcess(android.os.Process.myPid());
Editor editor = getSharedPreferences("clear_cache", Context.MODE_PRIVATE).edit();
editor.clear();
editor.commit();
trimCache(this);
super.onDestroy();
}
public static void trimCache(Context context) {
try {
File dir = context.getCacheDir();
if (dir != null && dir.isDirectory()) {
deleteDir(dir);
}
} catch (Exception e) {
// TODO: handle exception
}
}
public static boolean deleteDir(File dir) {
if (dir != null && dir.isDirectory()) {
String[] children = dir.list();
for (int i = 0; i < children.length; i++) {
boolean success = deleteDir(new File(dir, children[i]));
if (!success) {
return false;
}
}
}
// <uses-permission
// android:name="android.permission.CLEAR_APP_CACHE"></uses-permission>
// The directory is now empty so delete it
return dir.delete();
}
몇 가지 공유 환경 설정을 지울 경우이 솔루션이 훨씬 좋습니다.
@Override
protected void setUp() throws Exception {
super.setUp();
Instrumentation instrumentation = getInstrumentation();
SharedPreferences preferences = instrumentation.getTargetContext().getSharedPreferences(...), Context.MODE_PRIVATE);
preferences.edit().clear().commit();
solo = new Solo(instrumentation, getActivity());
}
컨텍스트를 사용하여 환경 설정, 데이터베이스 파일과 같은 앱 특정 파일을 지울 수 있습니다. Espresso를 사용한 UI 테스트에 아래 코드를 사용했습니다.
@Rule
public ActivityTestRule<HomeActivity> mActivityRule = new ActivityTestRule<>(
HomeActivity.class);
public static void clearAppInfo() {
Activity mActivity = testRule.getActivity();
SharedPreferences prefs =
PreferenceManager.getDefaultSharedPreferences(mActivity);
prefs.edit().clear().commit();
mActivity.deleteDatabase("app_db_name.db");
}
가장 간단한 방법은
private void deleteAppData() {
try {
// clearing app data
String packageName = getApplicationContext().getPackageName();
Runtime runtime = Runtime.getRuntime();
runtime.exec("pm clear "+packageName);
} catch (Exception e) {
e.printStackTrace();
}
}
데이터가 삭제되고 메모리에서 앱이 제거됩니다. 설정-> 응용 프로그램 관리자-> 앱-> 데이터 지우기의 데이터 지우기 옵션과 같습니다.
이렇게하면 데이터가 완전히 제거되고 앱이 강제 종료됩니다.
이 솔루션은 정말 도움이되었습니다.
아래 두 가지 방법을 사용하면 프로그래밍 방식으로 데이터를 지울 수 있습니다
public void clearApplicationData() {
File cacheDirectory = getCacheDir();
File applicationDirectory = new File(cacheDirectory.getParent());
if (applicationDirectory.exists()) {
String[] fileNames = applicationDirectory.list();
for (String fileName : fileNames) {
if (!fileName.equals("lib")) {
deleteFile(new File(applicationDirectory, fileName));
}
}
}
}
public static boolean deleteFile(File file) {
boolean deletedAll = true;
if (file != null) {
if (file.isDirectory()) {
String[] children = file.list();
for (int i = 0; i < children.length; i++) {
deletedAll = deleteFile(new File(file, children[i])) && deletedAll;
}
} else {
deletedAll = file.delete();
}
}
return deletedAll;
}
프로그래밍 방식으로이 작업을 수행하는 데 권장되는 방법은 무엇입니까?
유일하게 가능한 옵션은 adb shell pm clear package테스트 전에 ADB 명령을 실행 하는 것입니다. 가장 큰 문제는 테스트 실행과 셸 명령을 결합하는 두통입니다.
그러나 (Mediafe에서) 루트가 아닌 일반 장치에서 작동 할 수있는 솔루션이 제공되었습니다. 주석을 추가하기 만하면됩니다. 나머지는 모두 간단한 bash 스크립트 를 실행하여 수행됩니다 .
@ClearData테스트를하기 전에 주석을 추가 하고 테스트를 수행하기 전에 ADB clear 명령이 실행됩니다.
다음은 그러한 테스트의 예입니다.
@Test
@ClearData
public void someTest() {
// your test
}
아이디어는 다음과 같습니다
adb shell am instrument -e log true동일한 아이디어를 사용하면 다음과 같이 쉽게 지원할 수 있는 모든 옵션 이 있습니다.
주석 만 사용하십시오. 이처럼 :
@Test
@ClearData
@Tags(tags = {"sanity", "medium"})
@Parameterized.Repeat(count = 3)
public void myTest() throws Exception {
String param = params[index];
// ...
}
보너스! 🎁 실패한 테스트마다 :
일반적으로 테스트는 gradle 작업이 아닌 bash 스크립트에서 하나씩 실행되므로 더 많은 옵션을 쉽게 추가 할 수 있습니다.
📗 전체 블로그 게시물 : https://medium.com/medisafe-tech-blog/running-android-ui-tests-53e85e5c8da8
examples 예제가 포함 된 소스 코드 : https://github.com/medisafe/run-android-tests
이 6 년 질문에 대답하기를 바랍니다.)