Dependency Injection with Unique_Ptr to Mock

Dependency injection with unique_ptr to mock

After all, I ended up using this approach everywhere:

struct FooTest : public Test {
FooTest() : barMock{new BarMock} {
auto ptr = unique_ptr<BarMock>(barMock);
out.reset(new Foo(std::move(ptr)));
}

BarMock* barMock;
unique_ptr<Foo> out;
};

and it works fine with gtest/gmock.

Memory leak warning when using dependency injection using a unique_ptr containing a mocked interface

std::unique_ptr<Base> base = std::move(mock); is where the memory leak happens: *base will be destroyed as a Base, not a Mock, when base is destroyed.

The best fix is to add a virtual destructor (virtual ~Base() = default;), which you should have for a struct that has any other virtual members.

c++ Can I use std::unique_ptr with dependency injection?

Can you pass a unique_ptr to another class where the other class is
just "using" the pointer (without owning it??)?

In that case, change the pointer to reference :

class PaymentProcessor
{
public:
PaymentProcessor(CreditCardService & creditCardService_):
:creditCardService_(creditCardService_)
{
}

private:
CreditCardService &creditCardService_;
};

void DoIt()
{
creditCardService_.reset(new VisaCardService());
PaymentProcessor pp(*creditCardService_);
pp.ProcessPayment();
}

If you still want to use a pointer, then you need to use get method :

class PaymentProcessor
{
public:
PaymentProcessor(CreditCardService * creditCardService_):
:creditCardService_(creditCardService_)
{
}
private:
CreditCardService *creditCardService_;
};

void DoIt()
{
creditCardService_.reset(new VisaCardService());
PaymentProcessor pp(creditCardService_.get());
pp.ProcessPayment();
}


Related Topics



Leave a reply



Submit