构造函数 Mockito 中使用的模拟私有方法

Mock private method used in the constructor Mockito

我正在尝试测试 class 中的方法,其构造函数如下:

public class ResponseReader {

public ResponseReader(Socket client){
        try {
            bufferedReader = new BufferedReader(new InputStreamReader(client.getInputStream()));
            fileWriter = new BufferedWriter(new FileWriter(createFile()));
        } catch (IOException e) {
            throw new RuntimeException("Could not initiate ResponseReader");
        }
    }

"createFile"构造函数中的方法是私有的:

private static File createFile() {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("MMddhhmmss");
        String dateAsString = simpleDateFormat.format(new Date());
        File uartDataFile = new File("/root/Logs/" + dateAsString + "data.log");
        LOG.debug("Created data file {}", dataFile);
        return dataFile;
    }

当我尝试从此 class 测试方法时,我需要创建新对象,因此需要在创建 class:

的模拟之前模拟构造函数实例
  private Socket client;
    private InputStreamReader inputStreamReaderMock;
    private InputStream inputStreamMock;
    private BufferedReader bufferedReaderMock;
    private ResponseReader responseReaderMock;

@BeforeEach
public void init() throws Exception {
        inputStreamReaderMock = mock(InputStreamReader.class);
        bufferedReaderMock = mock(BufferedReader.class);
        inputStreamMock = mock(InputStream.class);
        client = mock(Socket.class);
        when(client.getInputStream()).thenReturn(inputStreamMock);

        responseReaderMock = Mockito.spy(new ResponseReader(client));
        PowerMockito.whenNew(BufferedReader.class).
                withArguments(inputStreamReaderMock).
                thenReturn(bufferedReaderMock);
}

一直有效到 "new FileWriter(createFile()))"。 有人可以建议如何模拟构造函数中使用的私有方法吗?所以我需要在模拟 class.

之前模拟这个方法

我已经通过在我的 ResponseReader 中添加设置器和空构造函数解决了这个问题 class:

  public ResponseReader(){}

    //this is used only for testing purpose
    public void setBufferedReader(BufferedReader bufferedReader) {
        this.bufferedReader = bufferedReader;
    }

    //this is used only for testing purpose
    public void setBufferedWriter(BufferedWriter bufferedWriter) {
        this.bufferedWriter = bufferedWriter;
    }

然后在测试中:

PowerMockito.whenNew(BufferedWriter.class).withArguments(fileWriterMock).thenReturn(bufferedWriterMock);
        PowerMockito.whenNew(BufferedReader.class).
                withArguments(inputStreamReaderMock).
                thenReturn(bufferedReaderMock);
        responseReaderMock.setBufferedReader(bufferedReaderMock);
        responseReaderMock.setBufferedWriter(bufferedWriterMock);