Franz Kafka
Franz Kafka

Reputation: 10841

Java: extracting interfaces just for testing

I want to test my code but I am noticing that some business logic classes demand on alot of objects with alot of state. But actually the communication between these classes is limited to 1 or 2 methods.

Is it good style if I create an interface with these 2 methods and in my test just create a mock object which does nothing?

The code will then have alot more interfaces which are not really needed, that's why I'm not sure if it's a good idea?

Upvotes: 6

Views: 144

Answers (3)

Cedric Beust
Cedric Beust

Reputation: 15608

Regardless of the testing aspect, if you notice that you only need a few specific methods in several parts of your code, I strongly recommend extracting an interface capturing these methods. It will clarify your architecture and decrease the coupling of your code (on top of making it easier to test).

Upvotes: 2

Don Roby
Don Roby

Reputation: 41137

As long as the interfaces capture important concepts, the more the merrier (imho). Down the road, you might even find yourself separating parts of the classes not related to the interface into other classes, or creating alternate implementations, and then they end up more clearly appropriate in the production code.

As noted in another answer, not all mocking frameworks require interfaces, and if they're really only to enable mocking, you might not need them.

If your mocks aren't actually doing anything, they might more appropriately be called stubs. Usually, real mocks are used to verify that calls to them are made correctly, and they have a very active role in the tests.

Upvotes: 2

John B
John B

Reputation: 32969

Although having interfaces is a good idea, you don't need interfaces to do mocking. EasyMock, Mockito and PowerMock all allow mocking of concrete classes. So given that, you can leave the code as is and use Mockito (my personal favorite) to mock the injected classes.

FYI, the mocks shouldn't "does nothing". They should be tested with each possible return value and each possible exception thrown.

Upvotes: 7

Related Questions