Saturday, February 28, 2015

Mocking java.net.URL

Introduction.Mocking
is a crucial part of the unit testing. It gives power to the
developer to push the limits of the logic without pleasing the
dependencies of the logic. Mocking has it's own forms for
different testing paradigms and also limitations. Recently
I have used mockito mock library to
develop some unit test cases. Even though Mokito is grate tool
for mocking it has few limitations ,by design Mokito can not mock/spy
final classes, anonymous classes or primitive types. Here I will
explain how I have found a workaround for final class problem.
ProblemHave
a look of "public
String getContent(URL url) throws
IOException"
method which takesjava.net.URL
as an argument and read the input stream from the http connection.
Here I need to mock java.net.URLis
a final class we often see in our codes , because of
above limitation we discussed above I can not get
HttpURLConnection form mocked URL instance.

SolutionSo
I started to dig in to other ways to create mock
URL instance with injected mock HttpURLConnection.
java.net.URL class has constructor which takes java.net.URLStreamHandler
as an argument. java.net.URLStreamHandler
is an interface with the method protected URLConnection openConnection(URL u ) throws IOException.So
if I can inject the mocked HttpURLConnection in to URLStreamHandleropenConnection()
method.Here
goes the unit test implementation.

About Me

Kalpa Senanayake is science and technology enthusiastic who has over three years of professional software development experience working on multi-tiered applications using Java and open source technologies. He is specialised in Java and and message oriented middleware systems. Currently working as a software engineer. He is Interested in a astrophysics, literature and stealth gaming.