PowerMock

1、普通方法的mock

public boolean mockPublic(File file) {
        return file.exists();
    }
    MockUtil mockUtil = new MockUtil();

    @Test
    public void testPublic() {
        File mockFile = PowerMockito.mock(File.class);
        PowerMockito.when(mockFile.exists()).thenReturn(true);
        Assert.assertTrue(mockUtil.mockPublic(mockFile));
    }

如果用 PowerMockito.doReturn(true).when(mockFile.exists());会抛异常

PowerMockito.when(file).ex.thenReturn(true);   --这种方式不行

但是可以使用  PowerMockito.doReturn(true).when(mockFile,"exists");   √

或者可以使用 PowerMockito.doReturn(true).when(mockFile).exists();    √

或者     PowerMockito.when(mockFile, "exists").thenReturn(true);           √

org.mockito.exceptions.misusing.UnfinishedStubbingException: 
Unfinished stubbing detected here:
-> at org.powermock.core.classloader.ClassloaderWrapper.runWithClassClassLoader(ClassloaderWrapper.java:51)

E.g. thenReturn() may be missing.
Examples of correct stubbing:
    when(mock.isOk()).thenReturn(true);
    when(mock.isOk()).thenThrow(exception);
    doThrow(exception).when(mock).someVoidMethod();
Hints:
 1. missing thenReturn()
 2. you are trying to stub a final method, which is not supported
 3: you are stubbing the behaviour of another mock inside before 'thenReturn' instruction if completed

说明:普通Mock不需要加@RunWith和@PrepareForTest注解。

2、Mock方法里new出来的对象

public boolean mockNewObj() {
        File file = new File("a");
        boolean b = file.exists();
        return b;
    }
    @Test
    public void testMockNewObj() throws Exception{
        MockUtil mockUtil = new MockUtil();

        File file = PowerMockito.mock(File.class);
        PowerMockito.whenNew(File.class).withAnyArguments().thenReturn(file);
        PowerMockito.doReturn(true).when(file,"exists");
        Assert.assertTrue(mockUtil.mockNewObj());
    }

需要加上@RunWith(PowerMockRunner.class) @PrepareForTest(MockUtil.class) 注解

3、Mock私有方法

    private int privateMethod() {
        return 2;
    }

    public int mockPrivate() {
        return privateMethod();
    }
    @Test
    public void testMockPrivate() throws Exception{
        MockUtil mockPrivateUtil = PowerMockito.mock(MockUtil.class);
        PowerMockito.when(mockPrivateUtil,"privateMethod").thenReturn(3);
//调用真实的方法
        PowerMockito.when(mockPrivateUtil.mockPrivate()).thenCallRealMethod();
        Assert.assertEquals(3,mockPrivateUtil.mockPrivate());
    }
或者spy
    @Test
    public void testMockPrivate2() throws Exception{
        MockUtil mockUtil = PowerMockito.spy(new MockUtil());
        PowerMockito.when(mockUtil, "privateMethod").thenReturn(3);
        Assert.assertEquals(3, mockUtil.mockPrivate());
    }

需要注解  @RunWith(PowerMockRunner.class) @PrepareForTest({MockUtil.class})

因为是私有方法,所以用  when(mockPrivateUtil,"privateMethod");doreturn和thenreturn都可以

4、Mock普通对象的final方法

    public boolean mockFinal(MockFinalUtil mockFinalUtil) {
        return mockFinalUtil.finalMethod();
    }
public class MockFinalUtil {
    public final boolean finalMethod() {
        return true;
    }
}
    @Test
    public void testMockFinal() throws Exception{
        MockUtil mockUtil = new MockUtil();
        MockFinalUtil mockFinalUtil = PowerMockito.mock(MockFinalUtil.class);
        PowerMockito.doReturn(false).when(mockFinalUtil).finalMethod();
        Assert.assertFalse(mockUtil.mockFinal(mockFinalUtil));
    }

需要注解 @RunWith(PowerMockRunner.class) @PrepareForTest({MockUtil.class,MockFinalUtil.class})

当需要mock final方法的时候,必须加注解@PrepareForTest和@RunWith。注解@PrepareForTest里写的类是final方法所在的类

如果是普通方法就不需要加注解

5、Mock普通类的静态方法

    public int mockStaic() {
        return MockStaticUtil.abc();
    }
public class MockStaticUtil {
    public static int abc() {
        return 2;
    }
}
    @Test
    public void testMockStatic() throws Exception{
        MockUtil mockUtil = new MockUtil();
        PowerMockito.mockStatic(MockStaticUtil.class);
        PowerMockito.when(MockStaticUtil.abc()).thenReturn(3);
        Assert.assertEquals(3, mockUtil.mockStaic());
    }

需要注解 @RunWith(PowerMockRunner.class) @PrepareForTest({MockStaticUtil.class})

注意,静态方法,不能用   PowerMockito.doReturn(3).when(MockStaticUtil.abc())

6、Mock系统类的静态和final方法

public class FlySunDemo {  
2     public String callSystemStaticMethod(String str) {  
3         return System.getProperty(str);  
4     }  
5 } 
import org.junit.Assert;  
 2 import org.junit.Test;  
 3 import org.junit.runner.RunWith;  
 4 import org.powermock.api.mockito.PowerMockito;  
 5 import org.powermock.core.classloader.annotations.PrepareForTest;  
 6 import org.powermock.modules.junit4.PowerMockRunner;  
 7   
 8 @RunWith(PowerMockRunner.class)  
 9 public class FlySunMockTest {  
10     @Test  
11     @PrepareForTest(FlySunDemo.class)  
12     public void testCallSystemStaticMethod(){  
13         FlySunDemo demo = new FlySunDemo();  
14         PowerMockito.mockStatic(System.class);  
15         PowerMockito.when(System.getProperty("aaa")).thenReturn("bbb");  
16         Assert.assertEquals("bbb", demo.callSystemStaticMethod("aaa"));  
17     }  
18 } 

**********************8

1、spy的用法与mock类似,用于生成一个类的虚拟对象

区别在于mock对象的方法默认逻辑是donothing(什么都不做,直接返回默认值)

spy对象的方法默认逻辑是callReadMethod(执行原对象对应的方法)

换个说法

mock默认mock所有的方法,spy默认全不mock

2、如果字段是@autowired注解,没有set方法,可以利用反射赋值

public interface UserDao {

    int select();
}
public class UserService {
    @Autowired
    private UserDao dao;

    public int select() {
        return dao.select();
    }
}
    @Test
    public void test() throws Exception{
        UserDao dao = PowerMockito.mock(UserDao.class);
        PowerMockito.when(dao.select()).thenReturn(3);
        UserService userService = new UserService();
        Field field = UserService.class.getDeclaredField("dao");
        field.setAccessible(true);
        field.set(userService, dao);
        Assert.assertEquals(3, userService.select());
    }

3、Assert.fail("")   AssertionError异常

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值