The Software Purist |

TAG | gMock



The Power of Mocks

Mocks are a powerful tool in your testing toolkit. Whether you’re doing test-driven development or not, mocks are absolutely powerful. I first encountered mocks when I started getting a bit heavier into Java development and discovered jMock. My first reaction was that it was amazing. Each mock and stub I would hand-code would take some careful planning and writing of code. The code was always similar and so felt repetitive, yet it was never such a big thing that I thought I had to roll my own heavy reusable mechanism to streamline the process. Then I saw jMock. What used to take me hours took minutes. What used to take 100 lines of code took 10. It was an amazing improvement from a testing standpoint, and removed a lot of the dread when writing unit tests.

If you’re not familiar with mocks, a mock object is an object used in place of a real object for simulating behavior. It’s a very powerful concept. When you’re doing unit tests, you’re often trying to test a unit (often an object) in isolation, so using mocks, whether manual or automated is essential. jMock made this easy. Then I was introduced to Mockito, which was the next step in simplifying the process. Mockito turned the 10 lines of code into about 4 and introduced one critically important concept.

With jMock, in some cases you needed to have an interface in order to mock behavior, so IIRC, you could only be guaranteed to effectively mock with an interface. Concrete classes may work in jMock, but take more finessing. Not so with the amazing Mockito. With Mockito, I could take just about any class and mock the behavior of it and it worked. Amazing library. In addition, it wasn’t overly verbose like jMock is.

Now, in the C++ community, mocking was generally a manual process. There were mocking libraries, but not until recently did we have one that really streamlined the process. Then I discovered gMock, which is an amazing library and really fills the gap for C++. It does about as much as you can in C++, considering the lack of reflection for this sort of task and again gives you the power of mocks like you can get easily in Java.

In conclusion, mocks are an essential part of my testing process and I highly recommend you use them. In future articles, I will try to discuss some sample usage with some examples.


· · · · · · ·

Theme Design by