私はgtest
とgmock
に新規です。呼び出された関数を模擬する方法を教えてください。コードカバレッジにも役立ちます。場合gtestやgmockを使って、呼び出された関数の戻り値をモックすることは可能ですか?
#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
何が私が間違っているのなら、私に知らせてください。 ...
ユニットテストの概念については、ドキュメントを参照してください。https://stackoverflow.com/documentation/unit-testing/topicsアイデアは、サンプルデータを使用してメソッドを呼び出し、その結果をあなたが知っているものと比較することです正しい結果。最初は、コードカバレッジに心配することなく、良いテストを書くことを始めました。 – Gerriet