Android 单元测试 - "logcat -c" 比预期更频繁地清除日志

Android unit testing - "logcat -c" is clearing logs more often than it's supposed to

我编写了一些单元测试来检查日志记录是否按预期工作。例如,这里是正在测试的方法之一:

// from my SampleObject class
public void configure(Context context) {

    Log.d(TAG, "Configuration done.");
}

我想在每次测试前刷新 LogCat,这样上次测试的日志就不会被提取。为此,我编写了一个从 setUp():

调用的 clearLogs() 方法
private void clearLogs() throws Exception {
    Runtime.getRuntime().exec("logcat -c");
}

public void setUp() throws Exception {
    super.setUp();
    clearLogs();
    SampleObject mSampleObject = new SampleObject();
}

这是我的单元测试:

public void testConfigure() throws Exception {
    String LOG_CONFIGURATION_DONE = "Configuration done.";
    boolean stringFound = false;
    mSampleObject.configure(new MockContext());
    Process process = Runtime.getRuntime().exec("logcat -d SampleObject:D *:S");
    BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(process.getInputStream()));
    String line = "";
    while ((line = bufferedReader.readLine()) != null) {
        if (line.contains(LOG_CONFIGURATION_DONE)) {
            stringFound = true;
            break;
        }
    }
    assertTrue("Log message for configure() not found", stringFound);
}

问题是即使 clearLogs() 仅在 setUp() 中调用,日志条目也会被清除。如果我注释掉 clearLogs(),则测试有效。有人知道我做错了什么吗?

几个星期后,我终于找到了原因:logcat -c 没有立即清除日志,而是需要几秒钟的时间。但是,该过程从测试应用程序的角度来看。结果,测试用例随后立即执行,并在日志仍在清除时运行。添加两秒的短暂延迟解决了问题。