【问题标题】:Challenge Activity - C++ Unit Testing of a Class挑战活动 - 类的 C++ 单元测试
【发布时间】:2020-01-22 23:51:42
【问题描述】:

为 addInventory() 编写一个单元测试,它有一个错误。称呼 带有参数的 redSweater.addInventory() 毛衣发货。打印 如果后续数量不正确,则显示错误。样本输出 给定初始数量为 10 的单元测试失败,并且毛衣发货为 50:

Beginning tests.
   UNIT TEST FAILED: addInventory()
Tests complete.

注意:UNIT TEST FAILED 前面有 3 个空格。

是的,这是一个 C++ 编程课程的作业。我试图从下面的类中添加各种成员对象但无济于事,不幸的是我被卡住了,想要一些关于如何学习和继续的提示,而不是答案。这是我到目前为止的代码:

#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;
   int sweaterInventoryBefore;

   sweaterInventoryBefore = redSweater.getQuantityRemaining();
   cin >> sweaterShipment;

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

   // FIXME add unit test for addInventory

   /* Your solution goes here  */
      redSweater.addInventory(sweaterShipment);
   if (redSweater.addInventory(sweaterShipment) != 50){
      cout << "   UNIT TEST FAILED: addInventory()\n";
   }

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

   return 0;
}

编辑:已解决,以下解决方案

   // FIXME add unit test for addInventory

   /* Your solution goes here  */
   redSweater.addInventory(sweaterShipment);
   if (redSweater.getQuantityRemaining() != sweaterShipment){
      cout << "   UNIT TEST FAILED: addInventory()\n";
   }

【问题讨论】:

  • 技术说明:Stack Overflow 不能很好地处理提示。偏好是具体的答案。看起来你在这里绊倒的是addInventory 没有返回任何东西,所以你没有什么可以测试的。然而(这里是提示)addInventory 的工作是修改quantityRemaining,所以你真正想做的是在addInventory 完成后确认quantityRemaining 具有正确的值。如何读取main 中的private 成员quantityRemaining 的值,我会留给你。
  • 感谢您的帮助,在您的解释后想通了。如何标记为已解决?

标签: c++ unit-testing


【解决方案1】:

最简单的单元测试:

InventoryTag tag;
bool success = true;
TEST(tag.getQuantityRemaining() == 0, "initial quantity is zero");
tag.addInventory(1);
TEST(tag.getQuantityRemaining() == 1, "expected inventory is now 1");

其中 TEST 是一些宏定义如下:

#define TEST(expression, msg) {if (!(expression)) {success = false; cout << "TEST_FAILED: " << msg << endl;}}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-16
    • 2016-06-06
    • 2012-05-14
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-04
    相关资源
    最近更新 更多