【问题标题】:Mock FileInputStream in FileReader can't work using PowerMockFileReader 中的 Mock FileInputStream 无法使用 PowerMock
【发布时间】:2016-04-12 03:54:36
【问题描述】:

我注意到在 FileReader 构造函数中创建了 FileInputStream。所以我要在 FileReader 类中模拟它,但它不能工作。有人能猜出来吗?

如下代码:

package util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStreamReader;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

@RunWith(PowerMockRunner.class)
@PrepareForTest({ FileReader.class, ContentReader.class})
public class FileReaderTest {

    @Test
    public void testGetContent() throws Exception {
        File file = PowerMockito.mock(File.class);
        InputStreamReader isr = new InputStreamReader(new ByteArrayInputStream("123".getBytes()));
        PowerMockito.whenNew(InputStreamReader.class)
                .withArguments(Mockito.any(FileInputStream.class)).thenReturn(isr);
        Assert.assertEquals("123", ContentReader.getContent(file));
    }

}

class ContentReader {

    public static String getContent(File file) throws IOException {
        String content = "unknown";
        BufferedReader in = null;
        in = new BufferedReader(new FileReader(file));
        content = in.readLine();
        in.close();
        return content;
    }

}

【问题讨论】:

  • ContentReader::getContent 等价于PidHelper::getPidFromFile ?
  • 谁给new InputStreamReader打电话?
  • @gontard,是的。对此感到抱歉。我改了代码
  • @ArthurZagretdinov,FileReader 继承自 InputStreamReader,所以当调用 new FileReader(fiel) 时,也会调用 new InputStreamReader。

标签: filereader powermock fileinputstream powermockito


【解决方案1】:

回答 - 这是不可能的,因为要模拟系统类,PowerMock 应该能够修改使用系统类的客户端类。在您的情况下,两个类:谁使用和使用什么都是系统类。更多你可以阅读here(它是关于系统类的静态调用,但对于模拟构造函数调用也是如此)

另外,请检查这一点:don't mock what you don't own。对你来说,这意味着:

  • 您应该通过可以模拟的 util 类从文件中读取数据
  • 为您的 util 类编写集成测试。如果ContentReader 是一个 util 类,那么你不应该为它编写单元测试。

【讨论】:

    猜你喜欢
    • 2011-07-06
    • 1970-01-01
    • 2016-07-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-17
    相关资源
    最近更新 更多