欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

PowerMock应用二:模拟new对象

程序员文章站 2022-06-12 21:26:39
...
来个简单的
@RunWith(PowerMockRunner.class)
@PrepareForTest(MockFile.class) 
public class MockFile {
	@Test
	public void testRegisterService2() throws Exception {
		String s="F:/aa.txt";
		File file=PowerMockito.mock(File.class);
//              PowerMockito.whenNew(File.class).withArguments(s).thenReturn(file);
		PowerMockito.whenNew(File.class).withArguments(Mockito.anyString()).thenReturn(file);
		PowerMockito.when(file.exists()).thenReturn(true);
		File a=new File(s);
		Assert.assertEquals(true, a.exists());
	}
}



再来个复杂的,模拟数据流
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
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)
// 注意这里,这个是new FileInputStream所在的类
@PrepareForTest({ AA.class })
public class MockWhenNew {
	@Test
	public void test() throws Exception {
		// 模拟数据流
		File file = PowerMockito.mock(File.class);

		FileInputStream is = PowerMockito.mock(FileInputStream.class);
		PowerMockito.whenNew(FileInputStream.class).withArguments(file).thenReturn(is);

		InputStreamReader ir = new InputStreamReader(new ByteArrayInputStream("123".getBytes()));
		PowerMockito.whenNew(InputStreamReader.class).withArguments(Mockito.any(FileInputStream.class)).thenReturn(ir);

		AA spy = new AA();
		Assert.assertEquals("123", spy.aa(file));
	}
}

class AA {
	public String aa(File file) throws Exception {
		FileInputStream in = new FileInputStream(file);
		InputStreamReader is = new InputStreamReader(in);
		BufferedReader reader = new BufferedReader(is);
		String line = "", s = "";
		while ((line = reader.readLine()) != null) {
			s += line;
		}
		return s;
	}
}