步骤:
1、添加依赖
testCompile "org.robolectric:robolectric:3.0"
//assertj 依赖
testCompile 'org.assertj:assertj-core:1.7.1'
//测试Fragment需要添加的依赖
testCompile "org.robolectric:shadows-support-v4:3.0"
2、建立Test类
3、配置Test环境
4、进行单元测试(三步:setUp、test、assert)
编写完后运行
部分代码如下:
1、添加依赖
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
androidTestCompile('com.android.support.test.espresso:espresso-core:2.2.2', {
exclude group: 'com.android.support', module: 'support-annotations'
})
compile 'com.android.support:appcompat-v7:24.2.1'
//安卓自带测试依赖
testCompile 'junit:junit:4.12'
//robolectric 依赖
testCompile "org.robolectric:robolectric:3.0"
//assertj 依赖
testCompile 'org.assertj:assertj-core:1.7.1'
//测试Fragment需要添加的依赖
testCompile "org.robolectric:shadows-support-v4:3.0"
}
android {
useLibrary 'org.apache.http.legacy'
}
2、编写代码(部分)
public class MainActivity extends AppCompatActivity implements OnClickListener{
private Button btnIntent;
private Button btnInverse; //点击改变checkBox状态
private Button btnShowDialog; //显示提示框
private Button btnShowToast;
private Button sendBroadcast;
private CheckBox checkBox;
private TextView textView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setTitle("test title");
initView();
addClick();
}
private void addClick() {
btnIntent.setOnClickListener(this);
btnInverse.setOnClickListener(this);
btnShowToast.setOnClickListener(this);
btnShowDialog.setOnClickListener(this);
sendBroadcast.setOnClickListener(this);
}
private void initView() {
btnIntent = (Button) findViewById(R.id.btn_intent);
btnInverse = (Button) findViewById(R.id.btn_inverse);
btnShowDialog = (Button) findViewById(R.id.btn_show_dialog);
btnShowToast = (Button) findViewById(R.id.btn_toast);
checkBox = (CheckBox) findViewById(R.id.checkbox);
textView = (TextView) findViewById(R.id.text_view);
sendBroadcast = (Button) findViewById(R.id.btn_send_broadcast);
}
boolean change = false;
@Override
public void onClick(View view) {
switch (view.getId()) {
case R.id.btn_intent:
startActivity(new Intent(MainActivity.this, SecondActivity.class));
break;
case R.id.btn_inverse:
if (change) {
checkBox.setChecked(true);
} else {
checkBox.setChecked(false);
}
change = !change;
break;
case R.id.btn_show_dialog:
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("builder").setMessage("this is a dialog").show();
break;
case R.id.btn_toast:
Toast.makeText(this, "this is the toast",Toast.LENGTH_SHORT).show();
break;
case R.id.btn_send_broadcast:
sendBroadcast(new Intent("com.leixiansheng.RECEIVER"));
break;
}
}
/**
* 加法
*/
public int add(int a, int b) {
return a+b;
}
@Override
protected void onResume() {
super.onResume();
textView.setText("onResume");
}
@Override
protected void onDestroy() {
super.onDestroy();
textView.setText("onDestroy");
}
}
3、测试环境搭建,编写测试代码
@RunWith(RobolectricGradleTestRunner.class)
@Config(constants = BuildConfig.class, sdk = 21)
public class MainActivityTest {
private MainActivity mainActivity;
private SecondActivity secondActivity;
private FirstActivity firstActivity;
private ThirdActivity thirdActivity;
private ActivityController<MainActivity> activityController;
private TextView textView;
private Button btnInverse;
private Button btnIntent;
private Button btnToast;
private CheckBox checkBox;
private Button showDialog;
private Button sendBroadcast;
@Before
public void setUp() throws Exception{
//获取活动实例
mainActivity = Robolectric.setupActivity(MainActivity.class);
firstActivity = Robolectric.setupActivity(FirstActivity.class);
secondActivity = Robolectric.setupActivity(SecondActivity.class);
thirdActivity = Robolectric.setupActivity(ThirdActivity.class);
//模拟onCreate onStart
activityController = Robolectric.buildActivity(MainActivity.class)
.create().start();
Activity activity = activityController.get();
textView = (TextView) activity.findViewById(R.id.text_view);
btnInverse = (Button) mainActivity.findViewById(R.id.btn_inverse);
checkBox = (CheckBox) mainActivity.findViewById(R.id.checkbox);
showDialog = (Button) mainActivity.findViewById(R.id.btn_show_dialog);
btnToast = (Button) mainActivity.findViewById(R.id.btn_toast);
btnIntent = (Button) firstActivity.findViewById(R.id.btn_intent);
sendBroadcast = (Button) mainActivity.findViewById(R.id.btn_send_broadcast);
}
/**
* 创建活动实例
*/
@Test
public void testActivity() {
assertThat(mainActivity).isNotNull();
// assertEquals("test title", mainActivity.getTitle().toString());
assertThat("test title").isEqualTo(mainActivity.getTitle());
}
/**
* 生命周期
* 只有使用 ActivityController 才能模拟安卓生命周期
*/
@Test
public void testLifestyle() {
// assertEquals("Hello World!",textView.getText().toString());
assertThat(textView.getText().toString()).isEqualTo("Hello World!");
//模拟 onResume
activityController.resume();
assertThat(textView.getText().toString()).isEqualTo("onResume");
//模拟 onDestroy
activityController.destroy();
assertThat(textView.getText().toString()).isEqualTo("onDestroy");
}
/**
* 测试跳转
*/
@Test
public void testMainActivity() {
//模拟点击动作
btnIntent.performClick();
//实际结果
ShadowActivity shadowActivity = Shadows.shadowOf(firstActivity);
Intent actualIntent = shadowActivity.getNextStartedActivity();
//结果判定
assertThat(actualIntent.getComponent().getClassName()).isEqualTo(secondActivity.getComponentName().getClassName());
}
/**
* UI 组件状态
*/
@Test
public void testViewState() {
checkBox.setChecked(true);
//模拟点击翻转按钮
btnInverse.performClick();
assertThat(!checkBox.isChecked()).isTrue();
btnInverse.performClick();
assertThat(checkBox.isChecked()).isTrue();
}
/**
* Dialog
*/
@Test
public void testDialog() {
showDialog.performClick();
//注意这里的AlertDialog 只支持 android.app 不是support v7
AlertDialog latestAlertDialog = ShadowAlertDialog.getLatestAlertDialog();
assertThat(latestAlertDialog).isNotNull();
assertThat(latestAlertDialog.isShowing()).isTrue();
}
/**
* 自定义方法测试(加法)
*/
@Test
public void testAdd() {
int result = mainActivity.add(10, 30);
assertThat(result).isEqualTo(40);
}
/**
* Toast
*/
@Test
public void testToast() {
btnToast.performClick();
String toastText = ShadowToast.getTextOfLatestToast();
assertThat(toastText).isEqualTo("this is the toast");
}
/**
* 访问资源文件
*/
@Test
public void testResources() {
Application application = RuntimeEnvironment.application;
String appName = application.getString(R.string.app_name);
assertThat(appName).isEqualTo("UnitTest");
}
/**
* Broadcast
*/
@Test
public void testBroadcast() {
sendBroadcast.performClick();
ShadowApplication shadowApplication = ShadowApplication.getInstance();
String action = "com.leixiansheng.RECEIVER";
Intent intent = new Intent(action);
intent.putExtra("EXTRA_USERNAME", "xiao ming");
BroadReceiver receiver = new BroadReceiver();
receiver.onReceive(RuntimeEnvironment.application,intent);
SharedPreferences preferences = shadowApplication.getSharedPreferences("account", Context.MODE_PRIVATE);
System.out.print(preferences.getString("USERNAME",""));
//比较结果
assertThat(preferences.getString("USERNAME","")).isEqualTo("xiao ming");
}
/**
* Service
*/
@Test
public void testService() {
Application application = RuntimeEnvironment.application;
RoboSharedPreferences preferences = (RoboSharedPreferences) application.getSharedPreferences("example", Context.MODE_PRIVATE);
SampleService service = new SampleService();
service.onHandleIntent(new Intent());
assertThat(preferences.getString("SAMPLE_DATA", "")).isEqualTo("sample data");
}
/**
* fragment
*/
@Test
public void testFragment() {
SampleFragment sampleFragment = new SampleFragment();
//此api可以主动添加Fragment到Activity中,因此会触发Fragment的onCreateView()
SupportFragmentTestUtil.startFragment(sampleFragment);
assertThat(sampleFragment.getView()).isNotNull();
}
}
代码覆盖率:
1、测试类右键,选择下图运行方式
2、在执行完后弹出的简略窗口选择导出即可查看详细代码覆盖率
赠人玫瑰,手有余香。您的支持是我创作最大的动力!