使用Powermock和mockito

来源:互联网 发布:思科acl应用到端口 编辑:程序博客网 时间:2024/04/28 04:48

使用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();}}


0 0
原创粉丝点击