目的
编写whenNew测试代码,模拟新建对象其方法的执行结果
准备工作
mockito、easymock、powermock使用(2)-准备工作
测试代码
import com.suning.work.controller.MockController;
import junit.framework.TestCase;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.InjectMocks;
import org.mockito.MockitoAnnotations;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import java.io.File;
@RunWith(PowerMockRunner.class)
@PowerMockIgnore("javax.management.*")
public class MockWhenNewTest extends TestCase {
@InjectMocks
MockController mockController;
@Before
public void setUp() throws Exception {
MockitoAnnotations.initMocks(this);
}
/**
* 当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。
* 注解@PrepareForTest里写的类是需要mock的new对象代码所在的类
*
* PrepareForTest 可以写在测试类或测试函数上效果一样
* @throws Exception
*/
@Test
@PrepareForTest(MockController.class)
public void test() throws Exception {
File file = PowerMockito.mock(File.class);
//模拟创建新对象的返回值
PowerMockito.whenNew(File.class).withArguments("system.properties").thenReturn(file);
//模拟方法的结果
PowerMockito.when(file.exists()).thenReturn(true);
boolean result= mockController.fileExist("system.properties");
System.out.println(result);
PowerMockito.when(file.exists()).thenReturn(false);
result= mockController.fileExist("system.properties");
System.out.println(result);
}
}
测试说明
/** * 当使用PowerMockito.whenNew方法时,必须加注解@PrepareForTest和@RunWith。 * 注解@PrepareForTest里写的类是需要mock的new对象代码所在的类 * * PrepareForTest 可以写在测试类或测试函数上效果一样 */ @PrepareForTest(MockController.class)
//模拟创建新对象的返回值 PowerMockito.whenNew(File.class).withArguments("system.properties").thenReturn(file); //模拟方法的结果 PowerMockito.when(file.exists()).thenReturn(true);
测试结果
true
false