gpt4 book ai didi

c++ - Google Mock 中的双重免费

转载 作者:行者123 更新时间:2023-12-01 22:09:25 27 4
gpt4 key购买 nike

我是 Google Test 和 Mock 框架的新手。

我只是尝试运行“Turtle”示例,它成功了。

但是,显示错误消息:双重释放或损坏 (!prev)。

MockTurtle.h

#include <gmock/gmock.h>

class MockTurtle : class Turtle {
MOCK_METHOD0(PenUp, void());
MOCK_METHOD0(PenDown, void());
MOCK_METHOD1(Forward, void(int distance));
MOCK_METHOD1(Turn, void(int degrees));
MOCK_METHOD2(GoTo, void(int x, int y));
MOCK_CONST_METHOD0(GetX, int());
MOCK_CONST_METHOD0(GetY, int());
};

Turtle.h

class Turtle {
virtual ~Turtle() {}
virtual void PenUp() = 0;
virtual void PenDown() = 0;
virtual void Forward(int distance) = 0;
virtual void Turn(int degrees) = 0;
virtual void GoTo(int x, int y) = 0;
virtual int GetX() const = 0;
virtual int GetY() const = 0;
};

Painter.h

class Painter    
{
       Turtle* turtle;
public:
       Painter( Turtle* turtle )
               :       turtle(turtle){}

       bool DrawCircle(int, int, int){
               turtle->PenDown();
               return true;
       }
};    

Main_test.cpp

#include <gtest/gtest.h>
#include <gmock/gmock.h>
#include "Painter.h"
#include "MockTurtle.h"

using ::testing::AtLeast;

TEST(PainterTest, CanDrawSomething) {
 MockTurtle turtle;
 EXPECT_CALL(turtle, PenDown())
     .Times(AtLeast(1));

 Painter painter(&turtle);

 EXPECT_TRUE(painter.DrawCircle(0, 0, 10));
}

int main(int argc, char** argv) {
 // The following line must be executed to initialize Google Mock
 // (and Google Test) before running the tests.
 ::testing::InitGoogleMock(&argc, argv);
 return RUN_ALL_TESTS();
}    

结果

[==========] Running 1 test from 1 test case.    
[----------] Global test environment set-up.
[----------] 1 test from PainterTest
[ RUN      ] PainterTest.CanDrawSomething
[       OK ] PainterTest.CanDrawSomething (0 ms)
[----------] 1 test from PainterTest (0 ms total)
[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (1 ms total)
[  PASSED  ] 1 test.
*** Error in `/home/user/workspace/google_mock_2/Debug/google_mock_2': double free or corruption (!prev): 0x098a8080 ***

我尝试用谷歌搜索,发现了几个相同的问题。人们说不应该使用mock作为全局变量。

但是我的示例没有使用全局变量。

请帮我解释一下为什么会发生双重免费。提前致谢!

最佳答案

上次,我在共享库中构建了谷歌测试和谷歌模拟。并且发生了错误(双重释放)。

我尝试构建为静态库。该错误不再出现。我不知道为什么,但我会调查以了解更多细节。

关于c++ - Google Mock 中的双重免费,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40762798/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com