How to test BufferedReader using Junit and Mockito

72 Views Asked by At

I have below code which reads CSV file and puts the values into HashMap on application startup. I am new to Junit, please suggest how to test below class.

@Component
public class Cache implements InitializingBean {
private static Map<String, String> map = new HashMap<>();

@Override
public void afterPropertiesSet() throws Exception {

try {
  BufferedReader reader = new BufferedReader(new FileReader("file.csv"));
  String details = null;
  while ((details = reader.readLine()) != null) {
    String[] values = details.split(",", 2);

    String firstString = values[0];
    String secondString = values[1];
    map.put(firstString, secondString);
  }
} catch (Exception ex) {
  ex.printStackTrace();
}
}
}
1

There are 1 best solutions below

0
Ivan Vakhrushev On

You don't have to test BufferedReader and you can't use Mockito here because you manually instantiate objects in code. Just split up your code: move out reading logic into new method (readCsvFile() for example) and write tests for it.

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.stereotype.Component;

@Component
public class Cache implements InitializingBean {
    private static Map<String, String> map = new HashMap<>();

    @Override
    public void afterPropertiesSet() {
        map.putAll(readCsvFile("file.csv"));
    }

    // readCsvFile can be easily tested
    static Map<String, String> readCsvFile(final String fileName) {
        final Map<String, String> buffer = new HashMap<>();
        try (BufferedReader reader = new BufferedReader(new FileReader(fileName))) {
            String details;
            while ((details = reader.readLine()) != null) {
                String[] values = details.split(",", 2);

                String firstString = values[0];
                String secondString = values[1];
                buffer.put(firstString, secondString);
            }
        } catch (IOException ex) {
            //ex.printStackTrace();
            // TODO better log exception here
        }
        return buffer;
    }
}

Then you can write a test for the Cache bean so that it isn't empty after startup