標籤:
這一次我主要用的是C#中的Regex來測試使用者輸入的字串是否合法。
這是我的UI介面:
- 三個輸入框允許使用者同時進行輸入
- 輸入後摁確定鍵即可輸出測試結果,摁下取消鍵即可重新進行輸入
- 輸出的測試資訊顯示在右側的輸出文字框中
測試案例:
第一步:等價類別型的劃分
| 有效等價類別 |
無效等價類別 |
| 長度:1到6 |
長度:0或者大於7 |
| 字元:a-z,A-Z,0-9 |
字元:英文/數字以外字元,控制字元,標點符號 |
第二步:測試案例的產生
| 編號 |
輸入字元 |
期望輸出 |
| 1 |
A |
有效輸入 |
| 2 |
Z |
有效輸入 |
| 3 |
55136s |
有效輸入 |
| 4 |
zAGsdf |
有效輸入 |
| 5 |
null |
無效輸入 |
| 6 |
@ |
無效輸入 |
| 7 |
空格 |
無效數入 |
| 8 |
*@#$%^ |
無效輸入 |
| 9 |
@123 |
無效輸入 |
| 10 |
12345# |
無效輸入 |
| 11 |
uyueiuwy |
無效輸入 |
測試結果:
下面是代碼部分:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
String[] str = new String[3];
str[0] = textBox1.Text;
str[1] = textBox2.Text;
str[2] = textBox3.Text;
Boolean res1=System.Text.RegularExpressions.Regex.IsMatch(str[0], @"^[a-zA-Z\d]{1,6}$");
Boolean res2 = System.Text.RegularExpressions.Regex.IsMatch(str[1], @"^[a-zA-Z\d]{1,6}$");
Boolean res3 = System.Text.RegularExpressions.Regex.IsMatch(str[2], @"^[a-zA-Z\d]{1,6}$");
if (res1 && res2 && res3)
{
label4.Text = "輸入正確!";
}
else
{
label4.Text = "輸入不合法,請重新輸入!";
}
}
private void button2_Click(object sender, EventArgs e)
{
textBox1.Text = "";
textBox2.Text = "";
textBox3.Text = "";
label4.Text = "請先輸入";
}
private void label4_Click(object sender, EventArgs e)
{
}
}
}
代碼中的核心部分就是Regex判段輸入字串是否合法的部分,我使用的Regex是:
@"^[a-zA-Z\d]{1,6}$"
即判斷每一位是否為字母或者數字,且出現的次數為1-6次。
軟體測試第三周之測試多個輸入的合法性