0
votes

Firstly, let me disclose that I'm NOT a Java developer, I currently develop in C#, so any assumptions or statements I make regarding Java may be incorrect or ill informed.

When writing unit tests in .Net with mocked objects, 99% of the time we mock interfaces. It's possible to mock classes but you're only going to be able to have control over the virtual (thus mockable) methods.

In Java, as methods are virtual by default then I imagine that mocking a class is going to be just the same as mocking an interface because everything is going to be overridden with mocking behaviour.

So, is it still best practice to have dependencies on interfaces (and consequently mock interfaces in unit tests) in Java, or do most Java developers use classes to reduce the number of types (no need for an interface)?

4
This is probably better suited for programmers.stackexchange.com but even there it might not be constructive.Brian Roach

4 Answers

1
votes

I've actually made the opposite transition--that is, mocking in java and then made the transition to csharp. The company I worked for traditionally still mocked up the interfaces, if the concrete indeed had one. Otherwise, we did mock the actual class which worked for the reasons you specified. So, from my experience, for the obvious dependency reasons, we did priority on the interfaces.

For java, we've chosen the Mockito mock framework, and I think it's worked beautifully.

http://code.google.com/p/mockito/

1
votes

Another good framework which I recommend is EasyMock.

http://easymock.org/

It has a low learning curve and I didn't have any problem when I used it.

1
votes

I'd mock interfaces in Java as well. I think that's the whole idea: clients only know about the interface reference type. You can inject in a mock implementation behind it and the client is none the wiser.

0
votes

Try Mockito http://code.google.com/p/mockito/. Very simple and still powerful!