当数据来自文本框时如何进行单元测试
How to unit test when data is coming from text box
我不熟悉编写单元测试用例。
我正在尝试使用 XUnit 来测试我的 c# 方法。
该方法接受来自 3 个文本框的数据。
我如何在没有 UI 的情况下对其进行单元测试并提供数据?
protected void btnSubmit_Click(object sender, EventArgs e){
string txt1= txtBox1.Text;
string txt2= txtBox2.Text;
string txt3= txtBox3.Text;
// this data is then manipulated and finally sent to a service
}
单元测试的目的是检查单击按钮时调用的方法是否运行无误。
单元测试的一大优点是它解决了代码中的 separation of concerns。它还指出了可以从封装中受益的领域。我可以提出的一个建议是封装代码的不同部分,以便您可以创建逻辑分离。下面是一个简单的例子:
protected void btnSubmit_Click(object sender, EventArgs e){
string txt1= txtBox1.Text;
string txt2= txtBox2.Text;
string txt3= txtBox3.Text;
string data = data_manipulation(txt1, txt2, txt3);
send_to_service(data, sender)
}
public string data_manipulation(string txt1, string txt2, string txt3){
//manipulate data
return manipulated_data;
}
public void send_to_service(string data, object sender){
//send data to service
}
这样一来,您就可以测试数据操作逻辑,而不必依赖于测试向服务发送数据。
我不熟悉编写单元测试用例。 我正在尝试使用 XUnit 来测试我的 c# 方法。
该方法接受来自 3 个文本框的数据。 我如何在没有 UI 的情况下对其进行单元测试并提供数据?
protected void btnSubmit_Click(object sender, EventArgs e){
string txt1= txtBox1.Text;
string txt2= txtBox2.Text;
string txt3= txtBox3.Text;
// this data is then manipulated and finally sent to a service
}
单元测试的目的是检查单击按钮时调用的方法是否运行无误。
单元测试的一大优点是它解决了代码中的 separation of concerns。它还指出了可以从封装中受益的领域。我可以提出的一个建议是封装代码的不同部分,以便您可以创建逻辑分离。下面是一个简单的例子:
protected void btnSubmit_Click(object sender, EventArgs e){
string txt1= txtBox1.Text;
string txt2= txtBox2.Text;
string txt3= txtBox3.Text;
string data = data_manipulation(txt1, txt2, txt3);
send_to_service(data, sender)
}
public string data_manipulation(string txt1, string txt2, string txt3){
//manipulate data
return manipulated_data;
}
public void send_to_service(string data, object sender){
//send data to service
}
这样一来,您就可以测试数据操作逻辑,而不必依赖于测试向服务发送数据。