0


Android Studio系列-Activity单元测试

import android.app.Activity;

import android.content.Intent;

import android.os.Bundle;

import android.view.View;

import android.widget.Button;

/**

  • Created by wwj_748 on 2016/2/22.17.08

*/

public class LoginActivity extends Activity implements View.OnClickListener{

private Button loginButton;

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_login);

loginButton = (Button) findViewById(R.id.btn_login);

loginButton.setOnClickListener(this);

}

@Override

public void onClick(View v) {

switch (v.getId()) {

case R.id.btn_login:

Intent intent = new Intent(this, IndexActivity.class);

startActivity(intent);

finish();

break;

}

}

}

public class IndexActivity extends Activity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_index);

}

}

代码很简单就不多解释。

新建Activity单元测试类

===============

package com.devilwwj.unittestdemo;

import android.content.Intent;

import android.test.ActivityUnitTestCase;

import android.test.suitebuilder.annotation.MediumTest;

import android.widget.Button;

/**

  • Created by wwj_748 on 2016/2/22.17.12

*/

public class LoginActivityTest extends ActivityUnitTestCase {

private Intent mLoginIntent;

// 要这样才不会报错

public LoginActivityTest() {

super(LoginActivity.class);

}

@Override

protected void setUp() throws Exception {

super.setUp();

mLoginIntent = new Intent(getInstrumentation().getTargetContext(), LoginActivity.class);

}

@MediumTest

public void testLoginButton_labelTest() {

startActivity(mLoginIntent, null, null);

final Button loginButton = (Button) getActivity().findViewById(R.id.btn_login);

final String buttonText = getActivity().getString(R.string.login);

// String buttonText = “xxxx”;

assertEquals(“Unexpected button ladel text”, buttonText, loginButton.getText());

}

@MediumTest

public void testLoginActivityMoveToIndex() {

startActivity(mLoginIntent, null, null);

final Button loginButton = (Button) getActivity().findViewById(R.id.btn_login);

// 测试Button的点击事件

loginButton.performClick();

final Intent intent = getStartedActivityIntent();

// 去判断是否为空,如果为空就说明跳转失败

assertNotNull(“Intent was null”, intent);

// 这一句是判断你在跳转后有没调finish()

assertTrue(isFinishCalled());

}

}

代码解释:继承ActivityUnitTestCase类创建一个针对具体Activity的单元测试类,这里只是针对LoginActiivty,其他Activity的测试也是类似的。里面创建了两个测试方法,testLoginButton_labelTest测试登录按钮的文本是否跟期望的值一致,testLoginActivityMoveToIndex方法测试点击按钮之后的跳转。

测试结果

====

测试


本文转载自: https://blog.csdn.net/2401_87373950/article/details/142419219
版权归原作者 2401_87373950 所有, 如有侵权,请联系我们删除。

“Android Studio系列-Activity单元测试”的评论:

还没有评论