Good day! I need to cover the next class with tests, how to do it correctly, I have never done it before.

public class FileCityProviderImpl implements CityProvider { @Override public List<String> getCityList(String path) throws IOException { BufferedReader reader = new BufferedReader(new FileReader(path)); String line; List<String> lines = new ArrayList<String>(); while ((line = reader.readLine()) != null) { lines.add(line); for (String s : lines) { } } return lines; } } 

    1 answer 1

    For a class to be easily tested, it is worth replacing the String path with the InputStream . Then, in the test, you can add the initial data into a string, wrap it in a ByteArrayInputStream and run it through the method.

    Like that:

     public class FileCityProviderImplTest { @Test public void testGoodInput() { String source = .... ; InputStream stream = new ByteArrayInputStream(source.getBytes("UTF-8")); List<String> cities = getCityList(stream); assertNotNull(cities); assertEquals(... , cities.size()); assertEquals(... , cities.get(0)); assertEquals(... , cities.get(1)); assertEquals(... , cities.get(2)); } @Test public void testEmptyInput() { InputStream stream = new ByteArrayInputStream("".getBytes("UTF-8")); List<String> cities = getCityList(stream); assertNotNull(cities); assertEquals(0 , cities.size()); } } 

    If for some reason you cannot change the method signature, create a temporary file using the File.createTempFile("temp-file-name", ".tmp") method File.createTempFile("temp-file-name", ".tmp") , fill it with data and transfer its name to your method. And then - also: a file with good data, a file with bad data, an empty file.