JUnit & stub example

How to stub for JUnit test case.

So far I showed you a unit test of a method, that doesn't depend on other classes, but often you must create a unit test for such a method. How to do that? You must create a stub for these other classes and write barebone implementation. Other popular solution of this problem is by mocking the classes.

In one of my projects I have this service class. This class has a method, that loads the latest version of the application from the internet and compares it with current version. If they differ, user will be notified and suggested to upgrade his application. Now I'd like to test this method: loadLatestVersion(). This method uses an instance of HttpClientService, which connects to some URL and downloads a file to temporary location. Next it will parse this file, retrieve first line and save it to an attribute "latestVersion".

First I'll create a JUnit test case for this class. First I will create an attribute of type VersionService. Next I will create a barebone test. Now I must supply to "versionService" attribute an instance of HttpClientService. It is a class, so I will extend it. If it was an interface, then I would implement it. I will create a class HttpClientServiceStub and I will implement a method downloadTemporaryFile.