UniversalDetectorUtil { public static String getDetectedEncoding(InputStream is) throws IOException { UniversalDetector detector = new UniversalDetector(null); byte[] buf = new byte[4096]; int nread; while ((nread = is.read(buf)) > 0 && !detector.isDone()) { detector.handleData(buf, 0, nread); } detector.dataEnd(); return detector.getDetectedCharset(); } private  UniversalDetectorUtil(); static String getDetectedEncoding(InputStream is); static String getDetectedEncoding(File file);  }
@Test public void getDetectedEncoding_A$InputStream_UTF8() throws Exception { String name = "UTF-8.txt"; InputStream is = IOUtil.getResourceAsStream(name); String actual = UniversalDetectorUtil.getDetectedEncoding(is); String expected = "UTF-8"; assertEquals(expected, actual); }
@Test public void getDetectedEncoding_A$InputStream_Shift_JIS() throws Exception { String name = "Shift_JIS.txt"; InputStream is = IOUtil.getResourceAsStream(name); String actual = UniversalDetectorUtil.getDetectedEncoding(is); String expected = "SHIFT_JIS"; assertEquals(expected, actual); }
@Test public void getDetectedEncoding_A$InputStream_T$IOException() throws Exception { InputStream is = mock(InputStream.class); when(is.read(any(byte[].class))).thenThrow(new IOException()); try { UniversalDetectorUtil.getDetectedEncoding(is); fail("Expected exception was not thrown!"); } catch (IOException e) { } }
@Test public void getDetectedEncoding_A$File() throws Exception { File file = new File("release/junithelper-config.properties"); String actual = UniversalDetectorUtil.getDetectedEncoding(file); String expected = null; assertEquals(expected, actual); }
@Test public void getDetectedEncoding_A$File_T$IOException() throws Exception { File file = mock(File.class); try { UniversalDetectorUtil.getDetectedEncoding(file); fail("Expected exception was not thrown!"); } catch (IOException e) { } }