您的位置:首页 > 移动开发

闰年测试非法输入的处理 简单安卓app 20150406

2015-04-06 18:17 537 查看
在软件测试的课上,老师介绍了闰年测试。闰年测试旨在检测某一年份是否为闰年,计算方式为四年一闰,百年不闰,四百年再闰。使用安卓实现这个小程序。

界面代码如下:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"

tools:context="${relativePackage}.${activityClass}" >

<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:text="@string/hello_world" />

<EditText
android:id="@+id/editText"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="23dp"
android:ems="10"
android:hint="@string/hint"
android:lines="1"
>
</EditText>

<Button
android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/editText"
android:layout_centerHorizontal="true"
android:text="@string/bt" />

</RelativeLayout>


结果如下:



在我的程序中,使用Integer.parseInt的方法获取editText中输入的年份。在没考虑非法字符的情况下,输入特殊字符而非年份。程序停止运行。



在android ADT的logcat中,可以看到程序运行的日志:



String转化为int类型失败。考虑非法字符,即输入年份不合法,无法转换成String类型,使用try,catch截获错误,最终代码如下

package com.leap.leapyear;

import android.app.Activity;
import android.os.Bundle;
import android.view.Gravity;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

public class MainActivity extends Activity {
private EditText mEditText;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

Button button = (Button) this.findViewById(R.id.button);
mEditText = (EditText) MainActivity.this.findViewById(R.id.editText);

button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
String number = mEditText.getText().toString();
checkLeap(number);
}
});
}

private void checkLeap(String number) {

int messageResId = R.string.false_toast;

try {
int year = Integer.parseInt(number);

if (year % 4 == 0) {
messageResId = R.string.true_toast;
}
if (year % 100 == 0) {
messageResId = R.string.false_toast;
}
if (year % 400 == 0) {
messageResId = R.string.true_toast;
}
}
catch (Exception e) {
messageResId = R.string.illegal_toast;
}

Toast toast = Toast.makeText(this, messageResId, Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER, 0, 0);
toast.show();
}
}


使用测试用例进行测试

有效等价类:被4整除而且不被100整除或可以被400整除

无效等价类:其他年份,非法字符,空

测试结果如下

测试结果:



















其他:

有更简单的问题解决办法,在输入框<EditText/>下加一行android:inputType="number",限制输入为数字,测试发现点击输入框输入法自动切换为数字输入,而且无法输入除数字以外的字符。如下:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: