Alok Save
Alok Save

Reputation: 206518

Mock objects in C++

What are Mock objects? Can you please explain the concept? How to make use of Mock objects in C++? Any source examples will be highly helpful.

Upvotes: 11

Views: 25117

Answers (4)

Eran Pe'er
Eran Pe'er

Reputation: 531

Fake-It is a simple mocking framework for C++. FakeIt uses the latest C++11 features to create an expressive (yet very simple) API. With FakeIt there is no need for re-declaring methods nor creating a derived class for each mock. Here is how you Fake-It:

struct SomeInterface {
  virtual int foo(int) = 0;
};

// That's all you have to do to create a mock.
Mock<SomeInterface> mock; 

// Stub method mock.foo(any argument) to return 1.
When(Method(mock,foo)).Return(1);

// Fetch the SomeInterface instance from the mock.
SomeInterface &i = mock.get();

// Will print "1"
cout << i.foo(10);

There are many more features to explore. Go ahead and give it a try.

Upvotes: 5

Sandeep
Sandeep

Reputation: 658

Google Mock is a framework for mocking of dependencies of the class being unit tested. The website also includes a good introduction.

Upvotes: 3

Damian Schenkelman
Damian Schenkelman

Reputation: 3535

In general, a mock object is referring to an instance of a class that as the name says "mocks" the functionality of the original class. This is usually simplified when coding against an interface, so when testing a component that depends on an interface, you simply implement the interface to return the results necessary to perform your tests.

You can find more information here, including the different kinds of mocks that are used for testing:

I hope this helps.

Thanks, Damian

Upvotes: 4

Anon
Anon

Reputation: 1330

Read up on mockcpp and you'll find the answers to your question. Mocks are great for testing purposes where you can focus on testing one thing and mocking the behavior of other pieces in the environment.

Upvotes: 3

Related Questions