我使用Gmock进行测试,我得到了一个类,其中所有方法都是静态的。例如
class A
{
static int Method1(int x,int y){return (x+y)};
};如何使用Gmock测试这个类。请帮帮我。谢谢
发布于 2017-08-16 00:36:23
在不修改代码的情况下,您无法做到这一点。但是你可以用存根对象链接你的应用程序。只需创建另一个“A类”实现并将其与您的测试应用程序链接即可。
发布于 2022-01-07 16:08:09
到目前为止,gmock还不支持模拟静态函数和非虚函数。当您在遗留代码中有一个虚拟方法,并且您能够将一个新的模拟类作为子类放入其中时,它就会起作用。我建议使用"jomock“来实现一个新的解决方案,它支持模拟遗留全局函数、静态方法和非虚拟方法,而无需更改遗留代码。
// for your example..
class A
{
static int Method1(int x,int y){return (x+y)};
};
#include "jomock.h"
TEST(JoMock, testStaticFunction)
{
EXPECT_CALL(JOMOCK(A::Method1), JOMOCK_FUNC(_,_))
.Times(Exactly(1))
.WillOnce(Return(1));
EXPECT_EQ(A.Method1(1,2), 1);
}
// this is a little modification from the jomock example.
// https://github.com/jonah512/jomock发布于 2018-01-28 15:06:02
你可以通过创建独立的模拟类来做到这一点,这个类不会从你需要模拟的类派生出来。下面是你将如何做到这一点。
步骤1:注释具有静态函数的类
// Comment the class
/*
class A
{
static int Method1(int x,int y){return (x+y)};
};
*/步骤2:创建一个与A同名的模拟类,并模拟其中的Method1。请注意,它不是从原始类派生的
class A {
public:
MOCK_METHOD2(Method1, int(int x, int y));
};让我们假设使用静态函数的类需要将其模拟为UsingA。下面是它的编写方法。
class UsingA {
A &a1;
public:
UsingA(A & _a1) : a1(_a1) {}
int CallFn() {
// Original function that needs to be commented
// return a1::Method1(10,25);
return a1.Method1(10, 20);
}
};下面是如何编写测试的方法
TEST(MyMockTest, Method1Test) {
A mstat;
UsingA ua(mstat);
EXPECT_CALL(mstat, Method1(_,_))
.Times(1)
.WillOnce(Return(100));
int retVal = ua.CallFn();
EXPECT_EQ(retVal,100);
}这可能不是最好的方式,但是服务于目的。希望能有所帮助
https://stackoverflow.com/questions/35859043
复制相似问题