Robolectric常用方法
程序员文章站
2022-04-25 22:11:53
...
标题1.Robolectric官网第一个例子
1)页面
<?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>
2)页面逻辑
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));
}
});
}
}
3)单元测试
@RunWith(RobolectricTestRunner.class)
public class WelcomeActivityTest {
@Test
public void clickingLogin_shouldStartLoginActivity() {
WelcomeActivity activity = Robolectric.buildActivity(WelcomeActivity.class).create().get();
activity.findViewById(R.id.login).performClick();
Intent expectedIntent = new Intent(activity, LoginActivity.class);
Intent actual = shadowOf(RuntimeEnvironment.application).getNextStartedActivity();
assertEquals(expectedIntent.getComponent(), actual.getComponent());
}
}
2.方法介绍
1)@RunWith(RobolectricTestRunner.class) 通过此注解定义Robolectric运行的TestRunner
2)单元测试类上还可以添加@Config(application = X.class,
shadows = {A.class, B.class, C.class,…}) shows中是写的是本测试类中用到的实现的shadow类,application指定测试类使用的application类
3)Robolectric.buildActivity() 用于构造Activity,create()函数执行后,该Activity会运行到onCreate周期,resume()则对应onResume周期,一般情况下单元测试只要到create()状态就可以了,但是如果开发重写onstart()/onResume()方法(比如在这里进行了一些事件绑定),就需要运行到这些状态了