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

最新文章

  1. Deep Learning 22:总结一些deep learning的基本知识
  2. 全栈开发必备的10款Sublime Text 插件
  3. 处理海量数据的高级排序之——快速排序(C++)
  4. 关于web api 2 客户端请求Post
  5. 6/8/9/10/11 Sprint2 看板和燃尽图
  6. 【CodeForces 602C】H - Approximating a Constant Range(dijk)
  7. Jquery暴力解数独
  8. ajax使用。
  9. iOS之文本属性Attributes的使用
  10. QTableWidget 导出到表格
  11. magento里get与post传值如何接收
  12. MVC3 Razor 根据不同页面使用不同Layout
  13. JSP 禁用脚本设置
  14. mfc--弹出文件夹对话框
  15. Mybatis配置详解
  16. c++ 套路多
  17. js深度克隆对象
  18. python 全栈开发,Day80(博客系统分析,博客主页展示)
  19. NN中BP推导及w不能初始化为0
  20. 004.KVM日常管理1

热门文章

  1. visual studio2017 无法添加引用 未能加载包ReferenceManagerPackage not such interface support 解决方法
  2. debian安装oracle jdk
  3. 聊聊数据库~6.SQL运维中篇
  4. centos7安装 go
  5. python 的for else语句
  6. 11.2.3 Redis的启动停止
  7. linux基础part2
  8. log4j2.xml的例子
  9. NVM安装配置
  10. [原创]关于tomcat启动时时候端口被占用,8080,8005,8009