Part 5 – Testing a function that calls static methods

We still need to write a test for our GrabPage class.  This should be super easy, except for one little problem.  Our friend, Jsoup, uses static methods and Mockito doesn’t mock-out static methods.  Now we need to add PowerMock.  A handy library that adds just what we need to Mockito.

Another issue comes to play that is fundamental to unit testing.  Namely, you never want to include any outside information in your tests.  Not only can this be a performance problem, but this external data can change, usually when you least desire it.  This causes your tests to fail randomly.  We need to keep everything under control. So, even though a webcrawler by nature uses outside data, we want to test with inside data.   Here’s what the test looks like:

The test HTML looks like this:

You can see that it has a few different types of hrefs.  These will exercise the filtering that goes on in the class.

Mocking Static Methods

Getting back to the mocking problem.  Here’s the code we want to exercise.  Notice that parse() is a static method.

When the code under test calls a static method it really causes grief for mocking.  You see, Mockito will inject mock objects into your objects allowing you to control things.  However, there is no object on a static method call to mock out.  That’s where PowerMock comes in.  Refer back to the testing code.  Lines 23-24 are preparatory.  They give control of the test runs to PowerMock.   Lines 38-39, tell PowerMock where we need his help.

We can also take advantage of this mocking to prevent our GrabPage object from actually accessing an external site.  We pre-parse a document from our resources (lines 31, 32) then inject that document into our test (line 39).

Happy days!  We have a test for our class, we don’t access external information, and we get around the static methods in Jsoup.