tags:

views:

75

answers:

2

I am trying to see how test cases can drive interface design.

Now, if I have an interface with a method:

public interface UserService { User getNextUser(); }

and if UserServiceImpl is an implementation of UserService, then as per my understanding of mock objects, I should only mock the dependencies of the UserServiceImpl, like a UserRepository, because only then am I actually testing behaviour, i.e. does UserServiceImpl call UserRepository or not.

But then, if I must write a UserServiceTest, without creating a UserServiceImpl, then the only way I see is to create a mock of UserService, which doesn't seem quite right.

Where am I going wrong with this?

A: 

I can't say I completely understood what you're trying to get at with your question, but the bottom line is that you can't test a plain interface. If there's no implementation, there's nothing for a unit test to test.

The only way an interface could be "wrong" is if it doesn't fulfill its design requirements, and that's something only a human can tell.

Matti Virkkunen
So, the preferrred way would be, create interface, create empty implementation, write first unit test, make unit test fail, simple code in implementation to make test case pass, generalize and repeat. Is this the right approach then? So, mocks wouldn't really help here...
Abhijeet Kashnia
Actually, I would first write the (not compilable) unit test. That would force me to think about how the interface should look. I derive the interface from that, create an empty implementation, make the testcase pass...
Lieven
A: 

Your test cases should drive interface design by having a client be required to call getNextUser() on an object. You might mock out an object for your tests of client.

Where there are a number of clients calling this method, you might want to create the interface at this point so that different host classes can provide different behaviour.

TDD (and obviously BDD) drives the development of behaviour. Interfaces are a good side-effect.

quamrana