您好,我想知道如何对以下方法进行单元测试:
public float calcNP()
{
int rowcount = dataGridView1.Rows.Count;
int[] colB = new int[rowcount];
float[] NP = new float[rowcount];
float avgNP = 0;
for (int i = 0; i < rowcount; i++)
{
colB[i] = Convert.ToInt32(dataGridView1.Rows[i].Cells[5].Value);
}
float min = colB.Min();
float max = colB.Max();
float a = 1, b = 10;
for (int i = 0; i < rowcount; i++)
{
NP[i] = (a + (colB[i] - min) * (b - a)) / (max - min);
avgNP = NP[i] + avgNP;
}
avgNP = (avgNP / rowcount) * 100;
return avgNP;
}
以及以下
public float calcIFact()
{
float ftp = calcFTP();
float NP = calcNP();
float IntFact = NP / ftp;
return IntFact;
}
和这个
public float calcFTP()
{
float ftp = 0;
if (chkFTP.Checked == true)
{
// ftp =(float)Convert.ToDouble(txtFTP.Text)/100;
ftp = (float)Convert.ToDouble(txtFTP.Text);
}
if (chkFTP.Checked == false)
{
int rowcount = dataGridView1.Rows.Count;
int[] colB = new int[rowcount];
for (int i = 0; i < rowcount; i++)
{
colB[i] = Convert.ToInt32(dataGridView1.Rows[i].Cells[5].Value);
}
// ftp = colB.Max() / 100;
ftp = colB.Max();
}
如果有人能给我一些很棒的例子。
基本上只需要一些简单的计算测试
答案 0 :(得分:2)
我们告诉你这样做:
// New method, not depending on a gridview. Testable.
public float calcNP_pure(int[] colB)
{
float[] NP = new float[colB.Length];
float avgNP = 0;
float min = colB.Min();
float max = colB.Max();
float a = 1, b = 10;
for (int i = 0; i < rowcount; i++)
{
NP[i] = (a + (colB[i] - min) * (b - a)) / (max - min);
avgNP = NP[i] + avgNP;
}
avgNP = (avgNP / rowcount) * 100;
return avgNP;
}
// Not testable
public float calcNP()
{
int rowcount = dataGridView1.Rows.Count;
int[] colB = new int[rowcount];
for (int i = 0; i < rowcount; i++)
{
colB[i] = Convert.ToInt32(dataGridView1.Rows[i].Cells[5].Value);
}
return calcNP_pure(colB);
}
这个新方法也应该进入一个新类,而不是坐在表单或其他UI元素上。最佳实践是针对接口进行编程并将所需的依赖项注入对象:
public interface INpCalculator
{
float CalcNP(int[] values);
}
public class NpCalculator : INpCalculator
{
public float CalcNP(int[] values)
{
...
return ...;
}
}
public partial class Form1 : Form
{
private INpCalculator _npCalculator;
public Form1(INpCalculator npCalculator)
{
InitializeComponent();
_npCalculator = npCalculator;
}
private float CalcNP()
{
int[] colB = dataGridView1.Rows
.Cast<DataGridViewRow>()
.Select(row => row.Cells[5].Value)
.ToArray();
return _npCalculator.CalcNP(colB);
}
}
现在计算器是可测试的,无需打开任何形式:
[TestMethod]
public void TestNpCalculator()
{
// Arrange
var sut = new NpCalculator();
var values = new int[] { 12, 7, 15, 3 };
// Act
float result = sut.CalcNP(values);
// Assert
Assert.AreEqual(123.456f, result);
}
顺便说一句:sut
代表&#34;正在测试的系统&#34;。
答案 1 :(得分:0)
在该方法的当前状态下,您的单元测试将需要手动创建datagrid对象并根据您的测试场景填充值。正如Daniel所建议的那样,你的方法“public float calcNP()”不应该使用数据网格,而是你可以将一个整数数组传递给方法(只传递你将在计算中使用的值)