FileHelper { public static File getItemFile(Context context, Configuration.Item item) { if (item.isDownloadable()) { try { return new File(context.getExternalFilesDir(null), java.net.URLEncoder.encode(item.location, "UTF-8")); } catch (UnsupportedEncodingException e) { e.printStackTrace(); return null; } } else { 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({Environment.class}) public void testGetItemFile() throws Exception { File file = new File("/dir/"); when(mockContext.getExternalFilesDir(null)).thenReturn(file); Configuration.Item item = new Configuration.Item(); item.location = "http: assertEquals(new File("/dir/http%3A%2F%2Fexample.com%2F"), FileHelper.getItemFile(mockContext, item)); item.location = "https: assertEquals(new File("/dir/https%3A%2F%2Fexample.com%2F"), FileHelper.getItemFile(mockContext, item)); item.location = "file:/myfile"; assertNull(FileHelper.getItemFile(mockContext, item)); mockStatic(Environment.class); when(Environment.getExternalStorageDirectory()).thenReturn(new File("/sdcard/")); item.location = "file:myfile"; assertNull(null, FileHelper.getItemFile(mockContext, item)); item.location = "ahost.com"; assertNull(FileHelper.getItemFile(mockContext, item)); }
@Test @Ignore("The exception throwing does not work") public void testGetItemFile_encodingError() throws Exception { File file = new File("/dir/"); when(mockContext.getExternalFilesDir(null)).thenReturn(file); Configuration.Item item = new Configuration.Item(); item.location = "https: assertEquals(new File("/dir/https%3A%2F%2Fexample.com%2F"), FileHelper.getItemFile(mockContext, item)); mockStatic(java.net.URLEncoder.class); when(java.net.URLEncoder.encode(anyString(), anyString())).thenThrow(new UnsupportedEncodingException("foo")); assertNull(FileHelper.getItemFile(mockContext, item)); }