4 - Google Mock 进阶篇 --使用Moc 如何调用一个已经存在冒牌对象(Fake)

如何调用一个已经存在模拟

对Foof对象里面的两个虚函数已经有一接口的Fake实现了,那么接下来google mock 如何在这么一个假冒对象基础上再实现自己的模拟呢?

如下代码:

1。首先: Foof类里面有两个虚函数: DoThis(), DoThat()

2。FakeFoof类已经对,这两个函数实现了假冒。

3。我们再创建一个:MockFoo 类继承于原始的Foof类,用gMock 来再次模拟它:关键用到:ON_CALL()宏 

通过WillByDefault这个来把假冒的FakeFoof加载进去。

4。 最后,在TEST()宏里面,可以像以前一样在你的测试中使用MockFoo。只是没有设置ON_CALL或是EXPECT_CALL()的行为期望返回值之类的期望,那Fake函数就会被调用

 

   当你用Google Mock来定义Mock类,你可以代理对象的默认行为给你已经有的Fake类,用


#include "pch.h"
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "MockFoo.h"

using ::testing::_;
using ::testing::AtLeast;
using ::testing::Invoke;

class Foof {
public:
	virtual ~Foof() {}
	virtual char DoThis(int n) = 0;
	virtual void DoThat(const char* s, int* p) = 0;
};

class FakeFoof : public Foof {
public:
	virtual char DoThis(int n) {
		return (n > 0) ? '+' :
			(n < 0) ? '-' : '0';
	}

	virtual void DoThat(const char* s, int* p) {
		*p = strlen(s);
	}
};


class MockFoof : public Foof {
public:
	// Normal mock method definitions using Google Mock.
	MOCK_METHOD1(DoThis, char(int n));
	MOCK_METHOD2(DoThat, void(const char* s, int* p));

	// Delegates the default actions of the methods to a FakeFoo object.
	// This must be called *before* the custom ON_CALL() statements.
	 
	void DelegateToFake() {
		ON_CALL(*this, DoThis(_))
			.WillByDefault(Invoke(&fake_, &FakeFoof::DoThis));
		ON_CALL(*this, DoThat(_, _))
			.WillByDefault(Invoke(&fake_, &FakeFoof::DoThat));
	}
private:
	FakeFoof fake_;  // Keeps an instance of the fake in the mock.
};


//对一个已经有假冒对象的类时的方法执行gMock测试
TEST(AbcTest, DelegateToFake) {
	MockFoof foof;
	foof.DelegateToFake(); // Enables the fake for delegation.

	// Put your ON_CALL(foo, ...)s here, if any.

	// No action specified, meaning to use the default action.
	EXPECT_CALL(foof, DoThis(5));
	EXPECT_CALL(foof, DoThat(_, _));

	int n = 0;
	EXPECT_EQ('+', foof.DoThis(5));  // FakeFoo::DoThis() is invoked.
	foof.DoThat("Hi", &n);           // FakeFoo::DoThat() is invoked.
	EXPECT_EQ(2, n);

	 
}

最终TEST()宏里面假冒的 是使用到已对FakeFoo里面的 。


编译结果:

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值