27 November 2008

Only mock types you own (revisited)

There was a brief discussion on the JMock mailing list recently where we helped out a new user. In the process, we noticed that he was mocking Java Set, which we tend to avoid, because it's not a type that we own—it's not in the domain of the problem we're trying to solve. The way I put it was,

We see a lot of people using, for example, List<House> when what they actually mean is Street. We try to use types we own that represent concepts in the domain, rather than built-in or library types which we keep for implementing these domain types. If the domain types are defined in terms of roles, then they're often appropriate for mocking.

Isiah followed up with an old post of his own.

I think we have a satisfied customer:

Thank you Steve and Isiah, I think I just took a large step in the world of TDD.

It's nice when that happens...


Mike J said...

Question. I need to verify classes to use OpenGL (C++). It is possible to mock OpenGL using Google Mocks.

Normally, I agree completely - don't mock types you own. However, in order to efficiently automate unit testing for OpenGL related objects, mocking out the relevant parts of the API seems to be the way to do it. This also allows for TDD, even with OpenGL development.

Note that since OpenGL is actually a procedural API, there's no mock object per se; the test code is linked against a mock library which provides GMock implementations of OpenGL. The production code thus uses OpenGL directly; only the tests arrange things to allow for mocking.

Do you folks have any other suggestions or ideas?

Steve Freeman said...

"Only mock types you own" is a "training wheels" rule, that helps to break through common misunderstandings about the technique. Sometimes you have to break it.

That said, maybe you should be mocking at a level about the OpenGL layer. Maybe not, but it's probably worth looking at.