如何使用Junit和Mockito测试BufferedReader

k3bvogb1  于 11个月前  发布在  其他
关注(0)|答案(1)|浏览(154)

我有下面的代码,读取CSV文件,并把应用程序启动时的值到HashMap。我是新的Junit,请建议如何测试下面的类。

@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();
}
}
}

字符串

s71maibg

s71maibg1#

你不需要测试BufferedReader,这里也不能使用Mockito,因为你需要在代码中手动示例化对象。你只需要将代码拆分:将阅读逻辑移到新方法中(例如readCsvFile()),然后为它编写测试。

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;
    }
}

字符串
然后,您可以为该高速缓存bean编写一个测试,使其在启动后不为空

相关问题