与AndroidJUnit进行进程间或adb通信

时间:2017-10-26 17:48:24

标签: android unit-testing adb android-instrumentation

我想知道,在仪器测试执行期间是否存在与系统通信的任何方式。 例如: 我有一个带有红外端口的手机。我可以通过私有SDK使用它,我也可以用我的应用程序调整它。在我的Instrumentation测试用例中,我想要在测试单独测试执行之前根据外部事件测试应用程序行为 它看起来像

@Test
public void test() throws Exception {
    setupExternalCondition(condition1_ON); // setup external transiver
    assertNotNull(IR.read());
    assertTrue(assertIR.write());

    setupExternalCondition(condition1_OFF); 
    assertNotNull(IR.read());
    assertFalse(IR.write());
}

这是一个非常简单的例子,但有很多"条件"和sdk更新频率到高。我无法手动完成所有这些验证,也无法询问" transiver& SDK团队"制作一个模拟状态列表,仅用于编写覆盖单元测试。因此,我想以某种方式将外部组件执行注入TestRuner,以便在本地计算机(或CI计算机)上接收事件(或测试用例执行前的testName)以设置外部条件。

简单的解决方案(我认为)在appUnderTest上运行tcp服务器并请求外部条件更改 - 我不确定是否可能,并且不确定稳定连接(wifi),因此可能是做adb。

有什么建议吗?

P.S:测试设备具有root权限。

1 个答案:

答案 0 :(得分:0)

所以,找到不错但不理想的解决方案。 仍然等待更好的主张,如果不是,这个答案对某人有帮助; 为了在本地机器和AndroidJUnitTest之间“构建桥梁”,我将下一个类添加到测试中:

class IPCServiceBridge extends BroadcastReceiver {
    private static final String FILTER_ID = "IPC_SERVICE";
    private static IPCServiceBridge sInstance;
    private boolean mIsPermitted;

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals("ipc.service.action")) {
            mIsPermitted = true;
        }
    }


    public static IPCServiceBridge getInstance() {
        if (sInstance == null) {
            sInstance = new IPCServiceBridge();
            IntentFilter filter = new IntentFilter();
            filter.addAction("ipc.service.action");
            Context context = InstrumentationRegistry.getContext();
            context.registerReceiver(sInstance, filter);
        }
        return sInstance;
    }

    public void sendIpcCommand(String commandName) {
        try {
            int i = 30;
            mIsPermitted = false;
            while (i > 0) {
                pub("request:" + commandName);
                Thread.sleep(1000);
                if (mIsPermitted) {
                    break;
                }
                i--;
            }
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        if (!mIsPermitted) {
            throw new RuntimeException("IPC service does not respond");
        }
    }

    private static void pub(String msg) {
        Log.e(FILTER_ID, msg);
    }
}

我启动adb logcat -s“filter_name”,解析并检查应该对InsttUnit测试应用哪个条件。当条件准备就绪时,我发回广播接收器并采取必要的行动。

@Test
public void test2() throws Exception {
    IPCServiceBridge.getInstance().sendIpcCommand("CONDITION#123");
}

工作得很好,但我不确定它会非常稳定。

相关问题