代码应该在单元测试或集成测试中

时间:2013-11-19 23:42:58

标签: c# unit-testing testing integration-testing

首先,我是测试的新手,所以这可能是一个愚蠢的问题。我目前正在为我的课程创建单元测试。我有一个属性,取决于可空属性将发送一个新的Comment对象到数据库。通常使用单元测试,我只需要确保一个对象被发送到我的模拟服务,并称之为好。但是,测试Comment对象上的值以确保它沿着正确的路径向下而不仅仅是假设它没有意义。以下是我正在测试的代码示例:

if (DeliveryDate != null)
{
   AddPartHistory("Delivery Date Changed from " + ((DateTime)DeliveryDate).ToShortDateString() + " to " + ((DateTime)value).ToShortDateString());
}
else
{
   AddPartHistory("Delivered Date of " + ((DateTime)value).ToShortDateString() + " was added.");
}

AddPartHistory函数将Comment对象(将文本保存在名为Entry的属性中)发送到数据库(或测试期间的Mock服务),并将其存储在名为NewPartHistory的属性中。以下是我认为可能更像是集成测试的代码:

vm.DeliveryDate = DateTime.UtcNow;
Assert.AreEqual("Delivered Date of " + ((DateTime)vm.DeliveryDate).ToShortDateString() + " was added.", vm.NewPartHistory.Entry);

OldDeliveryDate = vm.DeliveryDate;
vm.DeliveryDate = DateTime.UtcNow;
Assert.AreEqual("Delivery Date Changed from " + ((DateTime)OldDeliveryDate).ToShortDateString() + " to " + ((DateTime)vm.DeliveryDate).ToShortDateString(), vm.NewPartHistory.Entry);

所以,回到这个问题,我应该将这些代码留在单元测试中,还是转向集成测试。

更新

由于有很多关于我的AddPartHistory方法的讨论,现在就是这样。它只是填写PartHistory的标准数据(总是相同的),添加条目,然后使用新数据更新Listview

private void AddPartHistory(string historyText)
{
   NewPartHistory = new CdaService.PartHistory();
   NewPartHistory.EnteredBy = User.Current.UID;
   NewPartHistory.Entry = historyText;
   NewPartHistory.EntryDate = DateTime.UtcNow;
   NewPartHistory.PartId = ThisPart.Id;
   webService.Insert(NewPartHistory);
   GetPartHistory();
}

1 个答案:

答案 0 :(得分:2)

我会更改它以将新的Comment对象传递给AddPartHistory方法 - 而不是传递值来构建对象。这样,您可以对逻辑进行单元测试,包括构建注释对象。从AddPartHistory返回注释对象以使其更容易断言也是有帮助的。

将其移出这样的方法:

   NewPartHistory = new CdaService.PartHistory();
   NewPartHistory.EnteredBy = User.Current.UID;
   NewPartHistory.EntryDate = DateTime.UtcNow;
   NewPartHistory.PartId = ThisPart.Id;

   if()
   {  
      NewPartHistory.Entry = "Delivered Date of"......;
      return AddPartHistory(NewPartHistory );
   }
   else
   {
       NewPartHistory.Entry = "Delivery Date Changed from".....;
       return AddPartHistory(NewPartHistory );
   }

   //return comment object from AddPartHistory so that you can call this entire method and assert all properties