Robolectric Test-Drive Your Android Code

时间:2023-12-23 09:01:56

Running tests on an Android emulator or device is slow! Building, deploying, and launching the app often takes a minute or more. That's no way to do TDD. There must be a better way.

//原生的单元测试的运行时测试形式很慢,构建部署启动也会费很长时间,使用这个框架就是个比较好的办法

Wouldn't it be nice to run your Android tests directly from inside your IDE? Perhaps you've tried, and been thwarted by the dreadedjava.lang.RuntimeException: Stub!?

Robolectric is a unit test framework that de-fangs the Android SDK jar so you can test-drive the development of your Android app. Tests run inside the JVM on your workstation in seconds. With Robolectric you can write tests like this:

//robolectric是一个单元测试框架,测试运行在JVM中只需要几秒

@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 makes this possible by rewriting Android SDK classes as they're being loaded and making it possible for them to run on a regular JVM.

//robolectric让重写Android sdk类变得可能,因为这些类已经被加载然后在正常的JVM运行也变得可能

SDK, Resources, & Native Method Emulation

Robolectric handles inflation of views, resource loading, and lots of other stuff that's implemented in native C code on Android devices. This allows tests to do most things you could do on a real device. It's easy to provide our own implementation for specific SDK methods too, so you could simulate error conditions or real-world sensor behavior, for example.

Run Tests Outside of the Emulator

Robolectric lets you run your tests on your workstation, or on your Continuous Integration environment in a regular JVM, without an emulator. Because of this, the dexing, packaging, and installing-on-the emulator steps aren't necessary, reducing test cycles from minutes to seconds so you can iterate quickly and refactor your code with confidence.

No Mocking Frameworks Required

An alternate approach to Robolectric is to use mock frameworks such as Mockito or to mock out the Android SDK. While this is a valid approach, it often yields tests that are essentially reverse implementations of the application code.

Robolectric allows a test style that is closer to black box testing, making the tests more effective for refactoring and allowing the tests to focus on the behavior of the application instead of the implementation of Android. You can still use a mocking framework along with Robolectric if you like.