Rebolectic
在src中有三个包,分别是:test、androidTest 和java
test:是测试不涉及Activity,UI组件的纯Java方法。
直接在电脑上直接测试。
androidTest:涉及UI,Android组件的都在该路径下测试。
需要连接真机,或者模拟器进行测试。
java:项目代码在moudle中的build.gradle文件下依赖
testCompile "org.robolectric:robolectric:3.6.1"
- 主界面xml布局
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.mazaiting.robolectrictest.MainActivity">
<Button
android:id="@+id/btn_login"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="login"/>
<Button
android:id="@+id/btn_open"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="open"/>
</LinearLayout>
- MainActivity.java代码(项目中使用了ButterKnife框架)
public class MainActivity extends AppCompatActivity {
private static final String TAG = "MainActivity";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ButterKnife.inject(this);
}
@OnClick(R.id.btn_login)
public void login(){
Log.e(TAG, "login: 登录");
Toast.makeText(this, "登录", Toast.LENGTH_SHORT).show();
}
@OnClick(R.id.btn_open)
public void open(){
Intent intent = new Intent(MainActivity.this, LoginActivity.class);
startActivity(intent);
}
}
- test包下的测试MainActivityTest类
/**
* @author mazaiting
* @date 2017/12/26
*/
@RunWith(RobolectricTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MainActivityTest {
@Before
public void before(){
Logger.error("start");
}
@Test
public void clickLoginBtn(){
MainActivity activity = Robolectric.setupActivity(MainActivity.class);
activity.findViewById(R.id.btn_login).performClick();
Logger.error(ShadowToast.getTextOfLatestToast());
}
@Test
public void clickOpenBtn(){
MainActivity activity = Robolectric.setupActivity(MainActivity.class);
activity.findViewById(R.id.btn_open).performClick();
Intent expectedIntent = new Intent(activity, LoginActivity.class);
Intent actual = ShadowApplication.getInstance().getNextStartedActivity();
Logger.debug(expectedIntent.getComponent().toString());
Logger.debug(actual.getComponent().toString());
Assert.assertEquals(expectedIntent.getComponent(), actual.getComponent());
}
@After
public void after(){
Logger.error("after");
}
}
- 更多使用请查看官方文档