LogListener { List<String> getNewLogs(){ List<String> logs = new ArrayList<String>(); try { Process logcatProcess = runLogcatCommand("-d"); InputStreamReader stream = new InputStreamReader(logcatProcess.getInputStream()); BufferedReader reader = new BufferedReader(stream); String line; while ((line = reader.readLine()) != null){ logs.add(line); } runLogcatCommand("-c"); } catch (Exception ex){ utils.logIssue("Error trying to read logcat output", ex); } return logs; } LogListener(Context context, List<LoggingService> services, boolean wifiOnly); void start();  }
@Test public void testGetNewLogs() throws UnsupportedEncodingException { final Process mockLogcatProcess = mock(Process.class); String fakeLogs = "E/SomeApp: Foam Unit Testing Test Log Message\n" + "I/SomeApp: Test Second Log Message\n"; InputStream inputStream = new ByteArrayInputStream(fakeLogs.getBytes("UTF-8")); when(mockLogcatProcess.getInputStream()).thenReturn(inputStream); LogListener logListener = new LogListener(null, null, false){ @Override Process runLogcatCommand(String commandLineArgs) throws IOException { return mockLogcatProcess; } }; List<String> newLogs = logListener.getNewLogs(); assertNotNull(newLogs); assertEquals(2, newLogs.size()); assertEquals("E/SomeApp: Foam Unit Testing Test Log Message", newLogs.get(0)); assertEquals("I/SomeApp: Test Second Log Message", newLogs.get(1)); }
@Test public void testGetNewLogsException() { final RuntimeException exceptionToThrow = new RuntimeException("Unit Testing"); LogListener logListener = new LogListener(null, null, false){ @Override Process runLogcatCommand(String commandLineArgs) throws IOException { throw exceptionToThrow; } }; Utils mockUtils = mock(Utils.class); logListener.utils = mockUtils; logListener.getNewLogs(); verify(mockUtils).logIssue(eq("Error trying to read logcat output"), eq(exceptionToThrow)); }