博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
Robolectric之Shadows
阅读量:2062 次
发布时间:2019-04-29

本文共 2172 字,大约阅读时间需要 7 分钟。

官网介绍地址:

本文根据自己平时的使用对官网文档的一种理解

shadows出现的原因

Robolectric虽然创建了一个包含了真实的Android框架代码的运行时环境,但是还是有一些限制:

  1. Native code - Android native code cannot execute on your development machine. (Android本地代码不能在我们的开发计算机上执行)
  2. Out of process calls - There are no Android system services running on your development machine.(我们的开发计算机上没有跑Android系统服务)
  3. Inadequate testing APIs - Android includes next to no APIs suitable for testing.(Android没有可以用于测试的API)

为了解决以上问题,就有了shadows。每一个shadow都可以修改或扩展Android系统中相应的类。每当Android实例化一个类时,Robolectric就会找到他相应的shadow类,然后给他们之间建立联系

自定义shadow类

在自定义的shadow类上添加注解:@Implements(shadowClassName.class)

在shadow的那个方法上添加注解:@Implementation
比如我们有一个类是这样的

public class Person {
private String name; private int age; public String getName(String first, String second){
return first + second; } public int getAge(int age){
return age * 10; }}

我们要做这个类的shadow

@Implements(Person.class)public class PersonShadow {
@Implementation public String getName(String first, String second){
return "hello world"; }}

在测试类中,添加配置@Config(shadows = {PersonShadow.class,MyOtherCustomShadow.class}"),此测试类中调用Person的getName方法时就会映射到PersonShadow的getName上,因为getAge没有shadow方法,还会调用Person的方法

Shadowing 构造方法:

@Implements(TextView.class)public class ShadowTextView {
... @Implementation protected void __constructor__(Context context) {
this.context = context; } ...

@RealObject的使用

@Implements(Point.class)public class ShadowPoint {
@RealObject private Point realPoint; ... public void __constructor__(int x, int y) {
realPoint.x = x; realPoint.y = y; }}

使用了此注解到就会映射为真实的类,而不是shadow类;但是此对象的方法被调用还是会被Robolectric拦截

使用

1.在类上添加注解@Config(shadows = {PersonShadow.class,MyOtherCustomShadow.class}"),在单元测试中调用我们shadow的类的方法时就会走我们的shadow类

2.通过Shadows.shadowOf()获得类相应的shadow类(Robolectric实现了很多Android系统类的shadow类,在调用这些系统方法时,Robolectric会保证Shadow相应的方法会调用)

Intent actualIntent = shadowOf(context).getNextStartedActivity();        Intent expectedIntent = new Intent(currentActivity, ExceptActivity.class);        Assert.assertEquals(expectedIntent.getComponent(), actualIntent.getComponent());

用此方法来查看代码是否启动了正确的Activity

我们也可以配置让我们写的shadow方法在所有的类中都生效

转载地址:http://furlf.baihongyu.com/

你可能感兴趣的文章
(PAT 1096) Consecutive Factors (质因子分解)
查看>>
(PAT 1019) General Palindromic Number (进制转换)
查看>>
(PAT 1073) Scientific Notation (字符串模拟题)
查看>>
(PAT 1080) Graduate Admission (排序)
查看>>
Play on Words UVA - 10129 (欧拉路径)
查看>>
mininet+floodlight搭建sdn环境并创建简答topo
查看>>
【linux】nohup和&的作用
查看>>
【UML】《Theach yourself uml in 24hours》——hour4
查看>>
Set、WeakSet、Map以及WeakMap结构基本知识点
查看>>
【NLP学习笔记】(一)Gensim基本使用方法
查看>>
【NLP学习笔记】(二)gensim使用之Topics and Transformations
查看>>
【深度学习】LSTM的架构及公式
查看>>
【深度学习】GRU的结构图及公式
查看>>
【python】re模块常用方法
查看>>
剑指offer 19.二叉树的镜像
查看>>
剑指offer 20.顺时针打印矩阵
查看>>
剑指offer 21.包含min函数的栈
查看>>
剑指offer 23.从上往下打印二叉树
查看>>
剑指offer 25.二叉树中和为某一值的路径
查看>>
剑指offer 26. 数组中出现次数超过一半的数字
查看>>