Sometimes TDD Requires a Hammer

While there are myriad mocking libraries available for the Java platform, only a select few of these nifty frameworks is capable of mocking the non-mock-friendly modifiers of static and final. Static (or class) methods, while handy for factories, become a nuisance for a framework like Mockito, however, with the inclusion of PowerMock, you’ve got yourself a proverbial hammer.hammerj

As I wrote about previously, I had to deal with a 3rd party library that is used to integrate with a networked service. This library is essentially hardwired to interact with homebase, which naturally provides some challenges when trying to test ones code that relies on this library. Moreover, the said library contained a static method for creating instances of a specialized class, which, naturally, my code depended on.

PowerMock is made to work in concert with either EasyMock or Mockito; what’s more, it comes with a custom runner for inclusion in JUnit. I’m going to show you how to use PowerMock with Mockito as I happen to find Mockito’s syntax much more fluent than EasyMock’s.

For starters, you’ll need to use two class level annotations – @RunWith for specifying the PowerMockRunner class (this is a JUnit annotation) and another dubbed @PrepareForTest, which takes the class with static methods you wish to mock. @PrepareForTest is provided by PowerMock.

In my case, the class containing a static method is named QTP, accordingly; my test class looks like this:

@RunWith(PowerMockRunner.class)
@PrepareForTest(QTP.class)
public class CreateCommandTest {
  @Test
  public void testCreateRequest() throws Exception {}
}

Next, in your test method, you use PowerMokito’s mockStatic method, which takes the class (again) with static methods you wish to mock.

@Test
public void testCreateRequest() throws Exception {
  PowerMockito.mockStatic(QTP.class);
  //....
}

You can then mock a static method on the class you’ve been passing around to mockStatic and the @PrepareForTest annotation like you would normally do with Mockito. For instance, I can use the when method to specify what I want to happen when this static method is invoked.

@Test
public void testCreateRequest() throws Exception {
  PowerMockito.mockStatic(QTP.class);
  QTP qtpThing = mock(QTP.class); //normal Mockito mocking
  //QTP.create is static
  when(QTP.create("dm2q", "0C4F7501UDC8C1EB43B06C988")).thenReturn(qtpThing);
  //QTP.createRecord isn't static
  when(qtpThing.createRecord(any(Tckt.class))).thenReturn(new Long(1000000L));
  //...
}

Finally, you can use PowerMock to ensure your mocked static method is actually invoked. The requirements here are a bit funky; that is, it requires you first specify how many times with one line of code and then you actually call the static method.

@Test
public void testCreateRequest() throws Exception {
  //...
  PowerMockito.verifyStatic(Mockito.times(1));
  QTP.create("dm2q", "0C4F7501UDC8C1EB43B06C988");
  //...
}

Yeah, that’s sorta confusing, I know.

Nevertheless, as most people in the world of Java figured out long ago, static methods are somewhat difficult when it comes to testing. That is, while a method that conceptually has no state, at first glance, seems straightforward enough to test, the issues arise when that static method does something like hit a database or in my case, call a web service to a networked asset. There is no easy way to override such behavior (unless, of course, you pull out a hammer).

Static methods have a place. But when it comes to testing code, whether it be legacy or some 3rd party library, the static modifier requires a hammer and as I hope I’ve shown you, PowerMock is that hammer.
 

Reference: Sometimes TDD Requires a Hammer from our JCG partner Andrew Glover at the The Disco Blog blog.
Related Whitepaper:

Software Architecture

This guide will introduce you to the world of Software Architecture!

This 162 page guide will cover topics within the field of software architecture including: software architecture as a solution balancing the concerns of different stakeholders, quality assurance, methods to describe and evaluate architectures, the influence of architecture on reuse, and the life cycle of a system and its architecture. This guide concludes with a comparison between the professions of software architect and software engineer.

Get it Now!  

Leave a Reply


8 × seven =



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books