美文网首页Android
Android test check if command av

Android test check if command av

作者: JaedenKil | 来源:发表于2017-11-30 16:57 被阅读8次

If we wish to execute a shell command in android test, we may do this:

String command = "xxx";
Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
UiDevice mDevice = UiDevice.getInstance(instrumentation);
mDevice.executeShellCommand(command);

But if this command is unavailable, the test is likely to fail to complete:

Test run failed: Test run incomplete. Expected 1 tests, received 0

This error is probably caused by exception.
So perhaps check if the command exists first is necessary:

package com.mrvl.pck;


import android.app.UiAutomation;
import android.os.ParcelFileDescriptor;
import android.support.test.uiautomator.UiDevice;
import android.util.Log;

import java.io.IOException;

public class FakeMethod {

    private static final String TAG = "FAKE";

    int isCommandAvailable(UiDevice mDevice, String command) {
        int statusCode;
        try {
            String result = mDevice.executeShellCommand("which " + command);
           if (result.equals("")) {
               statusCode = 1;
           } else {
               statusCode = 2;
           }
        } catch (IOException e) {
            e.printStackTrace();
                statusCode = 3;
        }
        return statusCode;
    }
}

package com.mrvl.pck;


import android.app.Instrumentation;
import android.app.UiAutomation;
import android.support.test.InstrumentationRegistry;
import android.support.test.uiautomator.UiDevice;
import android.util.Log;

import org.junit.After;
import org.junit.AfterClass;
import org.junit.Test;

public class FakeTest {

    Instrumentation instrumentation = InstrumentationRegistry.getInstrumentation();
    UiDevice mDevice = UiDevice.getInstance(instrumentation);
    private static final String TAG = "FAKE";
    FakeMethod fakeMethod = new FakeMethod();
    UiAutomation mUiAutomation = instrumentation.getUiAutomation();

    @After
    public void tearDown() throws Exception {
        Log.i(TAG, "Tear down");

    }

    @Test
    public void testFakeMethod() {
        int statusCode_1 = fakeMethod.isCommandAvailable(mDevice, "ifccnfig");
        if (statusCode_1 == 2) {
            Log.i(TAG, "True");
        } else if (statusCode_1 == 1){
            Log.i(TAG, "False");
        } else {
            Log.i(TAG, "Error");
        }
        int statusCode_2 = fakeMethod.isCommandAvailable(mDevice, "ifconfig");
        if (statusCode_2 == 2) {
            Log.i(TAG, "True");
        } else if (statusCode_2 == 1){
            Log.i(TAG, "False");
        } else {
            Log.i(TAG, "Error");
        }
    }
}

Output:

I FAKE    : False
I FAKE    : True
I FAKE    : Tear down

相关文章

网友评论

    本文标题:Android test check if command av

    本文链接:https://www.haomeiwen.com/subject/exavbxtx.html