我注意到在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;
}
}发布于 2016-04-18 20:04:37
射击答案-这是不可能的,因为要模拟系统类,PowerMock应该能够修改使用系统类的客户端类。在您的情况下,这两个类:谁使用和所使用的是系统类。更多您可以阅读这里 (它是关于系统类的静态调用,但对于模拟构造函数调用也是如此)
另外,请检查这个好点:不要嘲笑你不拥有的东西。对你来说,这意味着:
ContentReader是一个util类,那么您不应该为它编写单元测试。https://stackoverflow.com/questions/36563343
复制相似问题