[英]How to Increment Count of Shared Ptr from Raw Ptr
我正在進行類單元測試,並且遇到了這個問題Device* device
/ mock的過早刪除:
這是我的SUT:
Effect::~Effect()
{
for (auto it = infoList.begin(); it != infoList.end(); ++it)
{
(*it)->device->Remove(this, (*it)->position);
delete *it;
}
infoList.clear();
}
HRESULT Effect::Add(Device* device, ULONG position)
{
Info* info = new Info;
info->device = device;
info->position= position;
auto result = device->Add(position);
if (result == E_FAIL) return E_FAIL;
//some other methods being called from 'device'
infoList.push_back(info);
}
而我的測試:
class EffectTest: public ::testing::Test
{
public:
void SetUp()
{
sut_ = std::make_unique<Effect>();
deviceMock_ = std::make_shared<DeviceMock>();
}
protected:
std::unique_ptr<Effect> sut_;
std::shared_ptr<DeviceMock> deviceMock_;
};
TEST_F(EffectTest, Add)
{
EXPECT_CALL(*deviceMock_, Add(_).WillRepeatedly(Return(S_OK));
EXPECT_CALL(*deviceMock_, Remove(_, _)).WillRepeatedly(Return(S_OK));
sut_->Add(deviceMock_.get(), 90);
}
由於我只在Effect :: Add()中傳遞了原始指針(模擬) deviceMock_.get()
(),因此引用計數不會增加。 測試比實際的SUT更早拆除,因此在調用Effect析構函數時deviceMock_已被刪除。 我的問題是..設備仍在Effect的析構函數中被調用,因此導致崩潰:
(*it)->device->Remove(this, (*it)->position);
在我能做些什么,以迫使任何想法deviceMock_
活路時~Effect
被稱為? 我可以強制deviceMock_引用計數僅通過原始指針Device* device
來增加嗎?
請注意,盡管我無法更改以下功能的簽名 :
HRESULT Effect::Add(Device* device, ULONG position)
由於這是一個API 。
請幫助! 謝謝!
在deviceMock_
中EffectTest
sut_
和deviceMock_
的EffectTest
:
class EffectTest: public ::testing::Test
{
public:
void SetUp()
{
sut_ = std::make_unique<Effect>();
deviceMock_ = std::make_shared<DeviceMock>();
}
protected:
std::shared_ptr<DeviceMock> deviceMock_;
std::unique_ptr<Effect> sut_;
};
成員變量從下到上刪除。 更改此設置將導致在DeviceMock之前刪除效果。
我終於想出了解決此問題的方法。 基本上,我將sut_
范圍從類級別更改為測試級別:
class EffectTest: public ::testing::Test
{
public:
void SetUp()
{
deviceMock_ = std::make_shared<DeviceMock>();
}
protected:
std::shared_ptr<DeviceMock> deviceMock_;
};
TEST_F(EffectTest, Add)
{
auto sut_ = std::make_unique<Effect>(); //THIS IS THE FIX!
EXPECT_CALL(*deviceMock_, Add(_).WillRepeatedly(Return(S_OK));
EXPECT_CALL(*deviceMock_, Remove(_, _)).WillRepeatedly(Return(S_OK));
sut_->Add(deviceMock_.get(), 90);
}
這樣, sut_
被破壞,而不是模擬。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.