gpt4 book ai didi

c++ - 是否可以使用 gtest 或 gmock 模拟被调用函数的返回值?

转载 作者:太空宇宙 更新时间:2023-11-04 13:00:56 24 4
gpt4 key购买 nike

我是 gtestgmock 的新手,请让我了解如何模拟被调用的函数。这也将帮助我提高代码覆盖率。

#include <stdio.h>
#include "gtest/gtest.h"

int ret()
{
return 5;
}

class A
{
public:
A();
int a;
int func();
};

A::A()
{
printf("This is constructor\n");
}

int A::func()
{
int iRet = ret(); /* When func() is called by gtest I would like to control the return value of ret() */
int iRet1 = ret();
/* Based on these two values some operations to be done */
printf("This is func. %d, %d\n", iRet, iRet1);
return iRet;
}

TEST (abc, xyz) {
A a;
EXPECT_EQ(5, a.func()); /* Here how to get different values of iRet and iRet1 for ret() function? */
}

int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

如果无法通过 gtest 和/或 gmock 实现,请向我推荐任何其他工具。

我还尝试了以下未按预期工作的东西:

int ret()
{
printf("Returning 5\n");
return 5;
}

int ret1()
{
int iRet = 10;
printf("Inside ret1\n");
iRet = ret();
if (iRet == 5)
{
printf("Original ret is called\n");
}
else if (iRet == 100)
{
printf("This is mocked function call\n");
}
else
{
printf("Opps! This should not happen\n");
}
return iRet;
}

class FooMock {
public:
MOCK_METHOD0(ret, int());
MOCK_METHOD0(ret1, int());
};

TEST (abc, xyz) {
FooMock mock;
EXPECT_CALL(mock, ret()).Times(1).WillOnce(Return(100));
mock.ret1();
}
int main(int argc, char **argv)
{
::testing::InitGoogleMock(&argc, argv);
return RUN_ALL_TESTS();
}

运行时出现以下错误:

$ ./a.out 
[==========] Running 1 test from 1 test case.
[----------] Global test environment set-up.
[----------] 1 test from abc
[ RUN ] abc.xyz
gtest.cpp:86: Failure
Actual function call count doesn't match EXPECT_CALL(mock, ret())...
Expected: to be called once
Actual: never called - unsatisfied and active
gtest.cpp:87: Failure
Actual function call count doesn't match EXPECT_CALL(mock, ret())...
Expected: to be called once
Actual: never called - unsatisfied and active
[ FAILED ] abc.xyz (0 ms)
[----------] 1 test from abc (0 ms total)

[----------] Global test environment tear-down
[==========] 1 test from 1 test case ran. (0 ms total)
[ PASSED ] 0 tests.
[ FAILED ] 1 test, listed below:
[ FAILED ] abc.xyz

1 FAILED TEST

如果我做错了什么,请告诉我...

最佳答案

因此,单元测试的理念是运行一些代码,并将结果与​​预期结果进行比较。您的代码使它比必须的更复杂。例如

#include <stdio.h>
#include "gtest/gtest.h"

int incBy5(const int a) {
return a+5;
}

TEST (abc, xyz) {
int x=17;
EXPECT_EQ(x+5, incBy5(x));
}

int main(int argc, char **argv)
{
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}

请参阅一般单元测试概念的文档,尤其是 google-test。这一切的模拟方面都随着更复杂的事情而出现,以测试您可能没有现成的一切(例如网络资源、数据库等),并且您创建了可以替换这些资源的模型。

关于c++ - 是否可以使用 gtest 或 gmock 模拟被调用函数的返回值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44256546/

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