FileHelper { public static FileDescriptor closeOrWarn(FileDescriptor fd, String tag, String message) { try { if (fd != null) Os.close(fd); } catch (ErrnoException e) { Log.e(tag, "closeOrWarn: " + message, e); } finally { return null; } }  static InputStream openRead(Context context, String filename); static OutputStream openWrite(Context context, String filename); static Configuration loadCurrentSettings(Context context); static Configuration loadPreviousSettings(Context context); static Configuration loadDefaultSettings(Context context); static void writeSettings(Context context, Configuration config); static File getItemFile(Context context, Configuration.Item item); static InputStreamReader openItemFile(Context context, Configuration.Item item); static int poll(StructPollfd[] fds, int timeout); static FileDescriptor closeOrWarn(FileDescriptor fd, String tag, String message); static T closeOrWarn(T fd, String tag, String message);  }
@Test @PrepareForTest({Log.class, Os.class}) public void testCloseOrWarn_fileDescriptor() throws Exception { FileDescriptor fd = mock(FileDescriptor.class); mockStatic(Log.class); mockStatic(Os.class); when(Log.e(anyString(), anyString(), any(Throwable.class))).then(new CountingAnswer(null)); testResult = 0; assertNull(FileHelper.closeOrWarn((FileDescriptor) null, "tag", "msg")); assertEquals(0, testResult); testResult = 0; assertNull(FileHelper.closeOrWarn(fd, "tag", "msg")); assertEquals(0, testResult); testResult = 0; doThrow(new ErrnoException("close", 0)).when(Os.class, "close", any(FileDescriptor.class)); assertNull(FileHelper.closeOrWarn(fd, "tag", "msg")); assertEquals(1, testResult); }
@Test @PrepareForTest(Log.class) public void testCloseOrWarn_closeable() throws Exception { Closeable closeable = mock(Closeable.class); mockStatic(Log.class); when(Log.e(anyString(), anyString(), any(Throwable.class))).then(new CountingAnswer(null)); testResult = 0; assertNull(FileHelper.closeOrWarn((Closeable) null, "tag", "msg")); assertEquals(0, testResult); testResult = 0; assertNull(FileHelper.closeOrWarn(closeable, "tag", "msg")); assertEquals(0, testResult); when(closeable).thenThrow(new IOException("Foobar")); testResult = 0; assertNull(FileHelper.closeOrWarn(closeable, "tag", "msg")); assertEquals(1, testResult); }