CommandUtility { public static List<String> getCommandsFromFile(String fileName, String... params) { List<String> commands = new ArrayList<>(); try (Stream<String> stream = Files.lines(Paths.get(ClassLoader.getSystemResource(fileName).toURI()))) { commands = stream .filter(line -> !line.startsWith("#") && (!line.isEmpty())) .map(line-> MessageFormat.format(line, params)) .collect(Collectors.toList()); } catch (URISyntaxException e) { e.printStackTrace(); } catch (IOException ioe) { ioe.printStackTrace(); } return commands; }  static List<String> getCommandsFromFile(String fileName, String... params);  }
@Test public void testCommandUtility() throws Exception{ List<String> commands = new ArrayList<>(); commands.add("# comment"); commands.add("ps -aef | grep {0}"); Stream<String> commandStream = commands.stream(); PowerMockito.mockStatic(Paths.class); PowerMockito.mockStatic(Files.class); PowerMockito.mockStatic(ClassLoader.class); URL url = PowerMockito.mock(URL.class); PowerMockito.when(ClassLoader.getSystemResource(Mockito.anyString())).thenReturn(url); PowerMockito.when(Paths.get(Mockito.anyObject())).thenReturn(mockedPath); PowerMockito.when(Files.lines(Mockito.any(Path.class))).thenReturn(commandStream); List<String> processedCommands = CommandUtility.getCommandsFromFile("test.txt", "nginx"); Assert.assertNotNull(processedCommands); Assert.assertTrue(processedCommands.get(0).contains("nginx")); }
@Test @Ignore public void testCommandUtilityIOException() throws Exception{ PowerMockito.mockStatic(Paths.class); PowerMockito.mockStatic(Files.class); PowerMockito.mockStatic(ClassLoader.class); URL url = PowerMockito.mock(URL.class); PowerMockito.when(ClassLoader.getSystemResource(Mockito.anyString())).thenReturn(url); PowerMockito.when(Paths.get(Mockito.anyObject())).thenReturn(mockedPath); PowerMockito.when(Files.lines(Mockito.any(Path.class))).thenThrow(new IOException("IO Exception!!")); List<String> processedCommands = CommandUtility.getCommandsFromFile("test.txt", "nginx"); Assert.assertNotNull(processedCommands); Assert.assertTrue(processedCommands.isEmpty()); }