So you want to test the add() method for actually invoking subscribeToNewsletter() and do NOT want to execute the logic from subscribeToNewsletter() in this test – e.g. since you’re already unit testing subscribeToNewsletter() somewhere else.

Then you create a PARTIAL mock of CustomerService, giving a list of methods you want to mock.

So add() within the CustomerService mock is the REAL thing you want to test and for the method subscribeToNewsletter() you now can write an expectation as usual.

Disclaimer:

Mocking partially like this only works with PUBLIC or DEFAULT methods. So for this one, I actually had to change subscribeToNewsletter() from PRIVATE to DEFAULT visibility to make it testable – which possible might not be desirable in all cases.

Using a string “subscribeToNewsletter” which matches an actual method name is not very refactoring safe. Preferable you should at least a constant to discriminate from being any ordinary string. Anyway, your unit test will break sooner or later anyway if this method changes name – and you’ll know 🙂

Follow me on Twitter

Ted Vinke

I'm a software developer and Java enthusiast. I like clean and modular code, enjoy Agile projects and have a passion for trying our new things. I try to learn and teach every day, and occasionally I'm even able to blog about it :-) I currently work for First8, a Java software development company based in the Netherlands.