在比较应该是不同的并且有多行的数据表时,应该在单元测试中进行什么样的测试?
[TestMethod]
public void ExecuteOutWithMultipleDataTables()
{
//Arrange
int id1 = TestOrderBuilder.New().Build();
DataTable dtDefault = CreateDefaultDataTable(id1, "OUT", "TableDesc", DateTime.Now);
//Act
object[] result = OracleDatabase.ExecuteOut(SqlStatements.Cursor, procedureParameters);
DataTable dtResults = result[0] as DataTable;
//Assert
Assert.IsNotNull(dtDefault);
Assert.IsNotNull(dtResults);
Assert.AreNotEqual(dtDefault, dtResults);
Assert.AreNotSame(dtDefault.Rows[0][0], dtResults.Rows[0][0]);
Assert.AreNotSame(dtDefault.Rows[0][1], dtResults.Rows[0][1]);
}
这是我已经写过的一些东西的一个例子,但我不确定我是否在正确的轨道上。
有人有什么建议吗?
Mac如果需要验证每一行和每一列的值,则需要编写一个helper方法。
同样,它看起来不像一个单元测试,因为它看起来你在调用真正的数据库,而不是模拟它。
可以是
下面的内容private bool IsTableSame(DataTable t1, DataTable t2)
{
if (t1 == null)
return false;
if (t2 == null)
return false;
if (t1.Rows.Count != t2.Rows.Count)
return false;
if (t1.Columns.Count != t2.Columns.Count)
return false;
if (t1.Columns.Cast<DataColumn>().Any(dc => !t2.Columns.Contains(dc.ColumnName)))
{
return false;
}
for (int i = 0; i <= t1.Rows.Count-1; i++)
{
if (t1.Columns.Cast<DataColumn>().Any(dc1 => t1.Rows[i][dc1.ColumnName].ToString() != t2.Rows[i][dc1.ColumnName].ToString()))
{
return false;
}
}
return true;
}
我已经包装了上面相同的帮助器方法来使用断言。它有助于调试单元测试。
private void AssertTableRecordsAreEqual(DataTable expectedTable, DataTable actualTable)
{
Assert.IsNotNull(actualTable, "Table is empty");
Assert.AreEqual(expectedTable.Columns.Count, actualTable.Columns.Count, "Number of columns in actual and expected tables are different");
Assert.AreEqual(expectedTable.Rows.Count, actualTable.Rows.Count, "Number of records in actual and expected tables are different");
Assert.IsFalse(expectedTable.Columns.Cast<DataColumn>().Any(dc => !actualTable.Columns.Contains(dc.ColumnName)), "Table column names are different");
for (int i = 0; i <= expectedTable.Rows.Count - 1; i++)
{
Assert.IsFalse(expectedTable.Columns.Cast<DataColumn>().Any(dc1 => expectedTable.Rows[i][dc1.ColumnName].ToString() != actualTable.Rows[i][dc1.ColumnName].ToString()), "Table row value is different");
}
}