【发布时间】:2021-05-18 15:52:26
【问题描述】:
我正在编写一个单元测试并比较两个对象以确保它们相同,但我收到错误 no operator "==" matches these operands -- operand types are: Item == Item
这是我的代码,有问题的行已注释:
SCENARIO("A container can be created, and items added and removed from it.", "[container]") {
GIVEN("A container and some items.") {
Container merchant("Merchant", "Merchant Inventory");
Item sword;
WHEN("An item is added to an empty container.") {
merchant.addItem(sword);
THEN("The item is in position 0 in the container.") {
Item firstItem = merchant.get_contents().front();
REQUIRE(firstItem == sword); // I'm trying to assert that the item in the vector that
} // is returned is the item that was entered.
}
}
}
Item 和 container 是在别处定义的类。
根据要求,这里是Item 类的定义:
class Item {
public:
Item();
};
就是这样 - 在我的队友编写正确的代码之前,它是一个占位符类。
容器背后的代码目前也很有限,但我认为相关部分如下:
class Container {
private:
std::vector<Item> contents; // Capcity limited to 10 to begin with
public:
Container(std::string name, std::string description);
std::vector<Item> get_contents();
};
我还没有定义Containers 中的方法,因为我要先编写测试代码。
【问题讨论】:
-
只是一个疯狂的猜测(没有看到
Item类的定义)但我想这是因为operator==没有为该类定义? -
您是否为
Item类重载了==?需要查看Item类实现才能确定,但我怀疑你需要这个:stackoverflow.com/questions/1691007/… -
您需要为您的班级编写自己的比较运算符。
-
“相同”是什么意思?如果你想知道它们是否是内存中的同一个对象,我想你可以比较像
&firstItem == &sword这样的地址。但是,这是假设向量存储引用而不是当前的副本。但是,如果您想知道一个对象的两个副本中的数据是否相同,则必须为该类实现==。
标签: c++ unit-testing catch2