使用powermock所需要的jar如下:
maven:
<!-- mock单元测试 start -->
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito</artifactId>
<version>${powermock.version}</version>
<scope>test</scope>
</dependency>
<!-- mock单元测试 end -->import java.io.File;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import com.yihaodian.wap.test.ClassDependency;
import com.yihaodian.wap.test.ClassUnderTest;
//必须要有
@RunWith(PowerMockRunner.class)
//需要模拟的类
@PrepareForTest({ClassUnderTest.class,File.class})
public class TestClassUnderTest {
@Test
public void testCallArgumentInstance() {
showClassLoader("testCallArgumentInstance");
File file = PowerMockito.mock(File.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(underTest.callArgumentInstance(file));
}
@Test
public void testCallInternalInstance() throws Exception {
showClassLoader("testCallInternalInstance");
File file = PowerMockito.mock(File.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.whenNew(File.class).withArguments("bbb").thenReturn(file);
PowerMockito.when(file.exists()).thenReturn(true);
Assert.assertTrue(underTest.callInternalInstance("bbb"));
}
@Test
public void testCallFinalMethod() {
showClassLoader("testCallFinalMethod");
ClassDependency depencency = PowerMockito.mock(ClassDependency.class);
ClassUnderTest underTest = new ClassUnderTest();
PowerMockito.when(depencency.isAlive()).thenReturn(true);
Assert.assertTrue(underTest.callFinalMethod(depencency));
}
private void showClassLoader(String methodName) {
System.out.println("=============="+methodName+"===============");
System.out.println("TestClassUnderTest: " + TestClassUnderTest.class.getClassLoader());
System.out.println("ClassUnderTest: " + ClassUnderTest.class.getClassLoader());
System.out.println("ClassDependency: " + ClassDependency.class.getClassLoader());
}
}
public class ClassDependency {
public boolean isAlive(){
return false;
}
}import java.io.File;
public class ClassUnderTest {
public boolean callArgumentInstance(File file) {
return file.exists();
}
public boolean callInternalInstance(String path) {
File file = new File(path);
return file.exists();
}
public boolean callFinalMethod(ClassDependency classDependency){
return classDependency.isAlive();
}
}
本文介绍如何使用PowerMock进行Java单元测试,包括依赖配置、基本用法及示例。通过模拟不可见方法、构造函数调用等场景,展示PowerMock的强大功能。
845

被折叠的 条评论
为什么被折叠?



