【问题标题】:Unit testing with classes使用类进行单元测试
【发布时间】:2017-12-10 00:45:33
【问题描述】:

为 addInventory() 编写单元测试。调用 redSweater.addInventory() 参数为毛衣发货。如果后续数量不正确,则打印显示的错误。给定初始数量为 10 且毛衣发货量为 50 的失败单元测试的样本输出: 开始测试。 单元测试失败:addInventory() 测试完成。 注意:UNIT TEST FAILED 前面有 3 个空格。


#include <iostream>
using namespace std;

class InventoryTag {
public:
   InventoryTag();
   int getQuantityRemaining() const;
   void addInventory(int numItems);

private:
   int quantityRemaining;
};

InventoryTag::InventoryTag() {
    quantityRemaining = 0;
}

int InventoryTag::getQuantityRemaining() const {
   return quantityRemaining;
}

void InventoryTag::addInventory(int numItems) {
   if (numItems > 10) {
      quantityRemaining = quantityRemaining + numItems;
   }
}

int main() {
   InventoryTag redSweater;
   int sweaterShipment = 0;
   int sweaterInventoryBefore = 0;

   sweaterInventoryBefore = redSweater.getQuantityRemaining();
   sweaterShipment = 25;

   cout << "Beginning tests." << endl;

   // FIXME add unit test for addInventory




   cout << "Tests complete." << endl;

   return 0;
}

【问题讨论】:

  • 我不知道如何在这个问题中为 addInventory 编写单元测试,任何帮助将不胜感激!
  • 这部分你看懂了吗:"调用redSweater.addInventory(),参数为sweaterShipment。"

标签: c++ unit-testing visual-c++


【解决方案1】:

在行业环境中,单元测试通常使用某种单元测试框架来完成,例如Google Test。如果您使用的是 Visual Studio,您可以在 VS here 中查看单元测试的基础知识。

你问题的开头写成这是一个学校项目或什么的。如果是这种情况,那么您可能不想要这些选项中的任何一个。

【讨论】:

    【解决方案2】:

    是否允许包含其他库?

    就个人而言,我会使用 cassert 库来编写单元测试。包含后就可以这样使用了:

    assert(1+1==2)
    

    如果不是真的会抛出错误。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-05-17
      • 2012-07-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多