在我的单元测试中,我想测试GameLauncher
根据Game
创建包含Object
个CharacterSelections
的{{1}}。在Java风格的伪代码中,测试将是:
Game game = gameLauncher.createGame(characterSelections);
assertThat(game.getObjects(), containsInAnyOrder(c1, c2, c3));
当我在c ++工作时,game->getObjects()
会返回vector<Object*>
。我正在使用指针向量,因为Object
是一种多态类型。
GMock#ContainerMatchers给出了容器的匹配器列表。由于STL容器使用operator==
来确定其元素之间的相等性(请参阅github/cpp-container-equality),因此我不能简单地使用UnorderedElementsAre(...),因为这将执行指针比较。
我有什么选择?
// redacted includes
class GameLauncherTest : public testing::Test {
// ... redacted ...
};
TEST_F(GameLauncherTest, launchesGameWithCharacterInstanceForSelectedCharacters) {
auto const characterSelections = new CharacterSelections();
characterSelections->add(new CharacterSelection(0, false, 1));
characterSelections->add(new CharacterSelection(3, false, 0));
characterSelections->add(new CharacterSelection(2, true, 1));
Game* const game = this->gameLauncher->launchGame(characterSelections);
auto const character0 = new Character(0, objectData1);
auto const character1 = new Character(1, objectData0);
auto const character2 = new Character(2, objectData1);
const vector<Object*> inGameObjects = game->getObjects();
// fails
EXPECT_THAT(inGameObjects, UnorderedElementsAre(character0, character1, character2));
delete character0;
delete character1;
delete character2;
delete characterSelections;
}
答案 0 :(得分:1)
您可以使用Pointee
匹配器取消引用指针:
EXPECT_THAT(inGameObjects,
UnorderedElementsAre(Pointee(*character0),
Pointee(*character1),
Pointee(*character2)));