在Android模拟器或设备运行测试很慢!构建,部署和启动应用程序每每须要一分钟或更长时间。
在Android直接从您的IDE内部运行测试岂不是很好?但容易碰到java.lang.RuntimeException: Stub!
Robolectric不依赖Android SDK jar的安卓单元测试框架,测试在JVM上运行,能够在几秒内完成。
示例:
html
@RunWith(RobolectricTestRunner.class) public class MyActivityTest { @Test public void clickingButton_shouldChangeResultsViewText() throws Exception { MyActivity activity = Robolectric.setupActivity(MyActivity.class); Button button = (Button) activity.findViewById(R.id.button); TextView results = (TextView) activity.findViewById(R.id.results); button.performClick(); assertThat(results.getText().toString()).isEqualTo("Robolectric Rocks!"); } }
Robolectric改写Android SDK中的类,使他们可能在普通的JVM上运行。
Robolectric视图和资源及本地C代码实现等东东加载,很容易地提供咱们本身的特定的SDK方法实现,好比模拟错误状况或现实世界的sensor行为。
运行测试模拟器以外
Robolectric,您能够在工做站上运行测试,或在常规JVM持续集成环境,没有一个模拟器。正由于如此,德兴,包装和安装 - 上的仿真器的步骤是没有必要的,减小分钟的测试周期秒钟,这样能够快速迭代,并有信心重构代码。
Robolectric的风格更接近黑盒测试,一般不须要Mockito等模拟框架,固然依旧能够与Mockito配合使用。java
Robolectric与Gradle或Maven配合比较好。新项目推荐使用Gradle。
build.gradle
python
testCompile“org.robolectric:robolectric:3.0”
测试使用注解便可:
android
@RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class) public class SandwichTest { }
注意必须指定constants指向由生成系统生成的BuildConfig.class。Robolectric使用类的常量来计算输出路径(Gradle使用), 不然Robolectric将没法找到manifest,resources或asset。
使用Maven构建
pom.xml:
git
<dependency> <groupId>org.robolectric</groupId> <artifactId>robolectric</artifactId> <version>3.0</version> <scope>test</scope> </dependency>
测试使用注解便可:
github
@RunWith(RobolectricTestRunner.class) public class SandwichTest { }
若是你引用项目之外的资源(即在AAR依赖)项目之外的资源,须要提供Robolectric一个指针指向AAR在构建系统。
Android Studioapache
Robolectric适用于Android Studio 1.1.0及之后版本。在"Build Variants" 中开启 unit test支持便可。Linux和Mac中须要编辑“run configurations”,设置工做目录为$MODULE_DIR$。api
Eclipse已经不推荐使用,可是能够安装m2e-android(不支持AAR)插件,导入Maven 工程, 点击 "Plugin execution not covered by lifecycle configuration"。
示例工程参见:https://github.com/robolectric/robolectric-samples。
app
activity的layout以下:
框架
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/login" android:text="Login" android:layout_width="wrap_content" android:layout_height="wrap_content"/> </LinearLayout>
咱们要编写测试断言当用户点击按钮时应用程序启动LoginActivity。
public class WelcomeActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.welcome_activity); final View button = findViewById(R.id.login); button.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View view) { startActivity(new Intent(WelcomeActivity.this, LoginActivity.class)); } }); } }
检查启动了对应的intent便可:
@RunWith(RobolectricTestRunner.class) public class WelcomeActivityTest { @Test public void clickingLogin_shouldStartLoginActivity() { WelcomeActivity activity = Robolectric.setupActivity(WelcomeActivity.class); activity.findViewById(R.id.login).performClick(); Intent expectedIntent = new Intent(activity, WelcomeActivity.class); assertThat(shadowOf(activity).getNextStartedActivity()).isEqualTo(expectedIntent); } }
注意:目前Robolectric只有API 16/19/21的实例。貌似还不支持API 23等。上述代码不能实际执行,实际执行的参见demo。
后期有空会把上面代码串成实例。
配置注解
定制Robolectric的主要方式是经过@Config注解。注释能够应用到的类和方法,同事也能够在基类中定制。
配置SDK级别
Robolectric基于manifest的targetSdkVersion运行代码,可更改设置SDK版本:
@Config(sdk = Build.VERSION_CODES.JELLY_BEAN) public class SandwichTest { @Config(sdk = Build.VERSION_CODES.KITKAT) public void getSandwich_shouldReturnHamSandwich() { } }
配置应用程序类
@Config(application = CustomApplication.class) public class SandwichTest { @Config(application = CustomApplicationOverride.class) public void getSandwich_shouldReturnHamSandwich() { } }
配置资源路径
Gradle和Maven有默认值,也可自定义:
@Config(manifest = "some/build/path/AndroidManifest.xml") public class SandwichTest { @Config(manifest = "other/build/path/AndroidManifest.xml") public void getSandwich_shouldReturnHamSandwich() { } }
默认资源目录res和assets。经过添加resourceDir和assetDir选项到@Config可改变这些值。
配置属性
@Config注解的内容能够在文件中定义robolectric.properties:
sdk=18 manifest=some/build/path/AndroidManifest.xml shadows=my.package.ShadowFoo,my.package.ShadowBar
系统属性
robolectric.offline - Set to true to disable runtime fetching of jars.
robolectric.dependency.dir - When in offline mode, specifies a folder containing runtime dependencies.
robolectric.dependency.repo.id - Set the ID of the Maven repository to use for the runtime dependencies (default sonatype).
robolectric.dependency.repo.url - Set the URL of the Maven repository to use for the runtime dependencies (default https://oss.sonatype.org/content/groups/public/).
robolectric.logging.enabled - Set to true to enable debug loggin
Gradle可在all部分为单元测试配置系统属性。例如,覆盖Maven仓库URL和ID:
android { testOptions { unitTests.all { systemProperty 'robolectric.dependency.repo.url', 'https://local-mirror/repo' systemProperty 'robolectric.dependency.repo.id', 'local' } } }
参考资料:
http://tools.android.com/tech-docs/unit-testing-support。
Robolectric2.2以前,大多数的测试直接调用构造函数 (new MyActivity()),而后手动调用的生命周期方法,如OnCreate()。ShadowActivity的方法(例如ShadowActivity.callOnCreate())也常常使用,他们是的ActivityController的前身。ActivityController在Robolectric2.0中引入的。
如今不会直接建立ActivityController,而是使用Robolectric.buildActivity()开始。一般能够这样:
Activity activity = Robolectric.buildActivity(MyAwesomeActivity.class).create().get();
上面建立MyAwesomeActivity实例并调用onCreate()。
要检查onResume()也简单:
ActivityController controller = Robolectric.buildActivity(MyAwesomeActivity.class).create().start(); Activity activity = controller.get(); // assert that something hasn't happened activityController.resume(); // assert it happened!
相似的方法也包括start(), pause(), stop(), and destroy(),好比测试整个建立生命周期:
Activity activity = Robolectric.buildActivity(MyAwesomeActivity.class).create().start().resume().visible().get();
能够带intent启动Activity:
Intent intent = new Intent(Intent.ACTION_VIEW); Activity activity = Robolectric.buildActivity(MyAwesomeActivity.class).withIntent(intent).create().get();
或恢复已保存实例的状态:
Bundle savedInstanceState = new Bundle(); Activity activity = Robolectric.buildActivity(MyAwesomeActivity.class) .create() .restoreInstanceState(savedInstanceState) .get();
更多资料参见http://robolectric.org/javadoc/latest/org/robolectric/util/ActivityController.html。
为了减小对应用外部依赖,Robolectric的shadow被分红各类附加包。主Robolectric模块只提供基础的Android SDK提供的shadow。
SDK Package | Robolectric Add-On Package |
---|---|
com.android.support.support-v4 | org.robolectric:shadows-support-v4 |
com.android.support.multidex | org.robolectric:shadows-multidex |
com.google.android.gms:play-services | org.robolectric:shadows-play-services |
com.google.android.maps:maps | org.robolectric:shadows-maps |
org.apache.httpcomponents:httpclient | org.robolectric:shadows-httpclient |
开发代码:
import android.app.Activity; import android.os.*; import android.view.View; import android.widget.Toast; import com.oppo.acs.st.STManager; import com.oppo.acs.st.demo.R; import java.util.HashMap; import java.util.Map; public class MainActivity extends Activity { /** Those data is just for test. */ private static final String DATA_TYPE_EXPOSE="cpd-app-expose"; private static final String DATA_TYPE_CLICK="cpd-app-click"; private static final String DATA_TYPE_DOWNLOAD="cpd-app-down"; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main_activity); } public void onBnExpose(View view){ Toast.makeText(this, "expose", Toast.LENGTH_SHORT).show(); /** *Record the expose event. */ STManager.getInstance().onEvent(this, wrapKeyMap(view.getId())); } public void onBnClick(View view){ Toast.makeText(this, "click", Toast.LENGTH_SHORT).show(); /** *Record the click event. */ STManager.getInstance().onEvent(this, wrapKeyMap(view.getId())); } public void onBnDownload(View view){ Toast.makeText(this,"download", Toast.LENGTH_SHORT).show(); /** *Record the download event. */ STManager.getInstance().onEvent(this, wrapKeyMap(view.getId())); } public void onBnBatchExpose(View view){ Toast.makeText(this,"batch expose.", Toast.LENGTH_SHORT).show(); int i=0; while (i++<100){ STManager.getInstance().onEvent(this,wrapKeyMap(view.getId())); } } private Map<String,String> wrapKeyMap(int viewId){ Map<String,String> keyMap=new HashMap<String,String>(); //those data is just for test. keyMap.put(STManager.KEY_ENTER_ID,"demo"); keyMap.put(STManager.KEY_TAB_ID,"MainActivity"); keyMap.put(STManager.KEY_AD_POS_ID,"1001"); keyMap.put(STManager.KEY_CATEGORY_ID,"10001"); keyMap.put(STManager.KEY_PAR_TAB_ID,"1001"); keyMap.put(STManager.KEY_PAR_POS_ID,"10001"); keyMap.put(STManager.KEY_AD_ID,"200"); keyMap.put(STManager.KEY_AD_TYPE,"cpd"); keyMap.put(STManager.KEY_AD_OWNER,"OPPO"); keyMap.put(STManager.KEY_CONTENT_ID,"contentId"); keyMap.put(STManager.KEY_CONTENT_CLS,"test"); keyMap.put(STManager.KEY_CONTENT_SIZE,"20K"); keyMap.put(STManager.KEY_PLAN_ID,"100"); keyMap.put(STManager.KEY_PRICE,"200.00"); keyMap.put(STManager.KEY_PAR_EVENT_ID,"001"); keyMap.put(STManager.KEY_TRACE_ID,"001"); keyMap.put(STManager.KEY_AB_TEST,"ATest"); keyMap.put(STManager.KEY_GRADE,"good"); keyMap.put(STManager.KEY_PROPERTY,"test demo"); keyMap.put(STManager.KEY_DISPLAY_TIME, String.valueOf(System.currentTimeMillis())); // keyMap.put(STManager.KEY_MODULE_ID,"Test"); keyMap.put(STManager.KEY_PAR_MODULE_ID,"Test_Par"); keyMap.put(STManager.KEY_CHANNEL,"Test"); keyMap.put(STManager.KEY_APP_ID,"1001"); // switch (viewId){ case R.id.expose_bn: case R.id.batch_expose_bn: /** *Data type of expose event. */ keyMap.put(STManager.KEY_DATA_TYPE, DATA_TYPE_EXPOSE); break; case R.id.click_bn: /** *Data type of click event. */ keyMap.put(STManager.KEY_DATA_TYPE,DATA_TYPE_CLICK); break; case R.id.download_bn: /** *Data type of download event. */ keyMap.put(STManager.KEY_DATA_TYPE,DATA_TYPE_DOWNLOAD); break; default: break; } return keyMap; } @Override public void onBackPressed() { super.onBackPressed(); /** *Report all statistics data before application exit. */ STManager.getInstance().onExit(this, new STManager.ExitListener() { @Override public void onFinish(boolean result) { /** * Exit the application when report statistics data finished. */ android.os.Process.killProcess(android.os.Process.myPid()); } }); } }
测试代码:
import android.app.Activity; import android.view.Menu; import android.widget.Button; import com.oppo.acs.st.demo.BuildConfig; import com.oppo.acs.st.demo.R; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.robolectric.Robolectric; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowToast; import junit.framework.Assert; import static org.robolectric.Shadows.shadowOf; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class) public class MainActivityTest { Activity activity; @Before public void setUp() throws Exception { activity = Robolectric.setupActivity(MainActivity.class); final Menu menu = shadowOf(activity).getOptionsMenu(); } @After public void tearDown() throws Exception { } @Test public void testOnBnExpose() throws Exception { Button button = (Button) activity.findViewById(R.id.expose_bn); button.performClick(); Assert.assertEquals("expose", ShadowToast.getTextOfLatestToast()); } @Test public void testOnBnClick() throws Exception { Button button = (Button) activity.findViewById(R.id.click_bn); button.performClick(); Assert.assertEquals("click", ShadowToast.getTextOfLatestToast()); } @Test public void testOnBnDownload() throws Exception { Button button = (Button) activity.findViewById(R.id.download_bn); button.performClick(); Assert.assertEquals("download", ShadowToast.getTextOfLatestToast()); } @Test public void testOnBnBatchExpose() throws Exception { Button button = (Button) activity.findViewById(R.id.batch_expose_bn); button.performClick(); Assert.assertEquals("batch expose.", ShadowToast.getTextOfLatestToast()); } }package com.oppo.acs.st; import android.app.Application; import java.util.List; import com.oppo.acs.st.demo.BuildConfig; import org.junit.runner.RunWith; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import static org.junit.Assert.*; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class) @PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" }) @PrepareForTest({STManager.class}) public class STManagerTest { private STManager sTManager; private Application application; @Before public void setUp() throws Exception { sTManager = STManager.getInstance(); sTManager.enableDebugLog(); application = RuntimeEnvironment.application; ShadowLog.stream = System.out; } @After public void tearDown() throws Exception { } @Test public void init() throws Exception { sTManager.init(application); List logs = ShadowLog.getLogs(); System.out.println(logs.size()); String result = readFile(); assertTrue(result.contains("has no initted.init!!")); } @Test (expected = Exception.class) public void initWithNullRaiseException() throws Exception { sTManager.init(null); } public String readFile() throws Exception { String result = ""; List logs = ShadowLog.getLogs(); for (int i = 0; i < logs.size(); i++) { // System.out.println(logs.get(i).toString()); result = result + ((ShadowLog.LogItem) logs.get(i)).msg; } return result; } }
安卓端基于日志的测试方法
package com.oppo.acs.st; import android.app.Application; import java.util.List; import com.oppo.acs.st.demo.BuildConfig; import com.oppo.acs.st.utils.Utils; import org.junit.Rule; import org.junit.runner.RunWith; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.powermock.api.mockito.PowerMockito; import org.powermock.core.classloader.annotations.PowerMockIgnore; import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.rule.PowerMockRule; import org.robolectric.RobolectricGradleTestRunner; import org.robolectric.RuntimeEnvironment; import org.robolectric.annotation.Config; import org.robolectric.shadows.ShadowLog; import static org.junit.Assert.*; @RunWith(RobolectricGradleTestRunner.class) @Config(constants = BuildConfig.class, sdk = 21) @PowerMockIgnore({ "org.mockito.*", "org.robolectric.*", "android.*" }) @PrepareForTest(Utils.class) public class STManagerTest { private STManager sTManager; private Application application; @Rule public PowerMockRule rule = new PowerMockRule(); @Before public void setUp() throws Exception { sTManager = STManager.getInstance(); sTManager.enableDebugLog(); application = RuntimeEnvironment.application; ShadowLog.stream = System.out; } @After public void tearDown() throws Exception { } @Test public void init() throws Exception { sTManager.init(application); List logs = ShadowLog.getLogs(); System.out.println(logs.size()); String result = readFile(); assertTrue(result.contains("has no initted.init!!")); } @Test public void initWithoutNetwork() throws Exception { PowerMockito.mockStatic(Utils.class); PowerMockito.when(Utils.isNetworkAvailable(application)).thenReturn(false); assertFalse(Utils.isNetworkAvailable(application)); sTManager.init(application); String result = readFile(); assertTrue(result.contains("no net!")); } @Test (expected = Exception.class) public void initWithNullRaiseException() throws Exception { sTManager.init(null); } public String readFile() throws Exception { String result = ""; List logs = ShadowLog.getLogs(); for (int i = 0; i < logs.size(); i++) { // System.out.println(logs.get(i).toString()); result = result + ((ShadowLog.LogItem) logs.get(i)).msg; } return result; } }
上面例子要特别注意必需要添加Rule才行。