I am trying to write unit tests in C++ and am facing an issue with creating mock objects for an external dependency using Fakeit. So we have a class similar to the following:
class A
{
int test_method()
{
B obj;
return obj.sendInt()
}
};
class B
{
int sendInt()
{
return 5;
}
};
Now let's say I want to write a unit test for test_method()
of class A
. When we call obj.sendInt()
I want to mock it and return a different value. I tried using fakeit but was not able to arrive at a solution.
I know this will be solved if we try to do a dependency injection of B
via constructor or in setter methods, but I don't want to do it as it would take some refactoring in existing consumers of A
.
For a similar scenario in Java, I would use PowerMockito and achieve the same using PowerMockito.whenNew
B mock = Mockito.mock(B.class);
PowerMockito.whenNew(B.class).withAnyArguments().thenReturn(mock);
Mockito.when(mock.test()).thenReturn(2);
A obj=new A();
assertEquals(obj.test(), 2);