Search code examples
javaandroidunit-testinglogcat

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


I wrote some unit tests to check whether logging is working as intended. For example, here is one of the methods being tested:

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

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

I want to flush LogCat before each test so that the logs from the previous test do not get picked up. To do that, I wrote a clearLogs() method that is called from setUp():

private void clearLogs() throws Exception {
    Runtime.getRuntime().exec("logcat -c");
}

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

And here is my unit test:

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);
}

The issue is that the log entry is cleared even though clearLogs() is only called in setUp(). The test works if I comment out clearLogs(). Anyone have an idea what I'm doing wrong?


Solution

  • After several weeks, I've finally discovered the cause: logcat -c does not clear the logs immediately but takes several seconds to do so. However, the process appears from the test application's point of view. As a result, the test case is executed immediately afterwards and runs while the logs are still being cleared. Adding a short delay of two seconds resolved the problem.