ExceptionPersister { @Nullable StoredException loadStoredExceptionData(String fileName) { StoredException storedException = null; FileInputStream in = null; try { in = context.openFileInput(fileName); if (in != null) { final InputStreamReader reader = new InputStreamReader(in, "UTF-8"); final Gson gson = new Gson(); storedException = gson.fromJson(reader, StoredException.class); } } catch (Exception ex) { utils.logIssue("Could not load file [" + fileName + "]", ex); } finally { closeStream(in); } return storedException; } ExceptionPersister(Context context); Map<String, StoredException> loadAll(); void store(StoredException storedException);  }
@Test public void testLoadStoredExceptionData() throws IOException { Context mockContext = mock(Context.class); File tempFile = File.createTempFile("foam_unit_testing_stored_exception", ".txt"); PrintWriter writer = new PrintWriter(tempFile); String storedExceptionData = "{" + "\"platform\":\"PAGERDUTY\"," + "\"message\":\"test message\"," + "\"threadName\":\"unit_testing_thread\"," + "\"stackTrace\":\"unit\ntesting\nstack\ntrace\"" + "}"; writer.println(storedExceptionData); writer.flush(); writer.close(); FileInputStream mockFileInputStream = new FileInputStream(tempFile); when(mockContext.openFileInput(anyString())).thenReturn(mockFileInputStream); ExceptionPersister exceptionPersister = new ExceptionPersister(mockContext); StoredException response = null; try { response = exceptionPersister.loadStoredExceptionData("foam_unit_testing_stored_exception.txt"); } catch (Exception ex){ fail("Failed to deserialize StoredException from the data [" + storedExceptionData + "]. Error: " + ex); ex.printStackTrace(); } assertNotNull(response); assertEquals(ServiceType.PAGERDUTY, response.platform); assertEquals("test message", response.message); assertEquals("unit_testing_thread", response.threadName); assertEquals("unit\ntesting\nstack\ntrace", response.stackTrace); assertTrue("Unable to clean up unit testing temp file [" + tempFile.getAbsolutePath() + "].", tempFile.delete()); }
@Test public void testLoadStoredExceptionDataException() throws FileNotFoundException { Context mockContext = mock(Context.class); Utils mockUtils = mock(Utils.class); Exception exceptionToThrow = new RuntimeException("Unit Testing"); when(mockContext.openFileInput(anyString())).thenThrow(exceptionToThrow); ExceptionPersister exceptionPersister = new ExceptionPersister(mockContext); exceptionPersister.utils = mockUtils; exceptionPersister.loadStoredExceptionData("some_file.txt"); verify(mockUtils).logIssue(eq("Could not load file [some_file.txt]"), eq(exceptionToThrow)); }