zoukankan      html  css  js  c++  java
  • powermock, 强力模拟

    1. powermock是基于mockito或者easymock,TestNG之上的mock;
    2. 提供了对于静态函数,私有函数的mock
    4. 通过mock价值是直接使用的类;因为只有mock返回的代理实例才会有“预期”行为。反之,如果一个模拟的类是在测试代码中间接被使用,则mock失效,如果你无法把mock的实例(对象代理)传递给测试场景中需要使用到的内容。比如测试代码是topTask,Platform,Platform中内部通过调用RuleService来进行获取规则数据,Platform并没有提供接口为RuleService赋值,那么你即使模拟了RuleService来获取某个规则数据,无效,因为Platform中使用的实例和mock实例是两个实例。
     
    上代码:
    基类
    public class ClassA {
    public boolean getResult() {
    return false;
    }
     
    public int caculatePublic(int a, int b) {
    return caculate(a, b);
    }
     
    private int caculate(int a, int b) {
    return a + b;
    }
     
    public static int getValue() {
    return 1;
    }
    }
     
    测试类:
    import org.junit.Test;
    import org.junit.runner.RunWith;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
     
    import static org.junit.Assert.*;
    import static org.powermock.api.mockito.PowerMockito.*;
     
    /**
    * @author Lorry
    *
    */
    @RunWith(PowerMockRunner.class)
    @PrepareForTest(ClassA.class)
    public class TestClassA {
    @Test
    public void test() {
    try {
    ClassA ca = mock(ClassA.class);
    assertFalse(ca.getResult());
    when(ca.getResult()).thenReturn(true);
    assertTrue(ca.getResult());
    } catch (Exception e) {
    e.printStackTrace();
    fail();
    }
    }
     
    @Test
    public void testStatic() {
    assertEquals(1, ClassA.getValue());
    mockStatic(ClassA.class);
    when(ClassA.getValue()).thenReturn(10);
    assertEquals(10, ClassA.getValue());
    }
     
    //@Test
    public void testPrivate() {
    try {
    //ClassA ca = spy(new ClassA());
    //assertEquals(3, ca.caculatePublic(1, 2));
    //when(ca.caculatePublic(Mockito.anyInt(), Mockito.anyInt())).thenCallRealMethod();
    //when(ca, "caculate", 1, 2).thenReturn(99);
    //assertEquals(99, ca.caculatePublic(1, 2));
    } catch (Exception e) {
    e.printStackTrace();
    fail();
    }
    }
    }
  • 相关阅读:
    关于GIS从业人员的定位
    《企业应用架构模式》读书笔记(4)
    各大网络、软件巨头涉足Web GIS
    流水帐(2005.5)
    Xtreme Suite 和 Toolkit 9.6发布
    一个算法问题
    推荐2个最近使用的软件
    linux之pmap命令
    linux 文件系统简介
    百度脚本笔试题两道
  • 原文地址:https://www.cnblogs.com/xiashiwendao/p/6941985.html
Copyright © 2011-2022 走看看