luni, 10 august 2009

Java si Mocking - PowerMock

In previous posts I talked about testing python code through injected dependencies. The same idea can be achieved in Java even if it's a little trickier. After I had studied a couple of mocking libraries for java I decided to use PowerMock because it is very close to mocker library for python. This library improves EasyMock and in the latest release it supports integration with Mockito. It worth mentioning some unique features of this library:
  • mocking static functions/methods
  • mocking private functions/methods
These features are extremely important but hard to implement in other testing frameworks. For a better understanding of PowerMock I present a small example.

class Calculator {
public static int add(int a1, int a2) {
return a1 + a2;
}
}

class Operatii {
public int operatieComplexa(int a1, a2) {
int a = Calculator.add(a1, a2);
return ++a;
}
}

@RunWith(PowerMockRunner.class)
@PrepareForTest({Calculator.class})
class TestOperatii {
@Test
public void testOperatieComplexa() {
PowerMock.mockStatic(Calculator.class);
EasyMock.expect(Calculator.add(1, 2).andReturn(3);

PowerMock.replayAll();

Operatii obj = new Operatii();
int ret = obj.operatieComplexa(1, 2);

PowerMock.verifyAll();

Assert.assertEquals(4, ret);
}
}

This is all. When you run the test the code will use an injected method instead of using the static method from Calculator class. Some elements need to be explained:

  • @RunWith(PowerMockRunner.class). It tells JUnit to use PowerMockRunner class for running the tests(it won't work without this line because PowerMock implements a custom class loader).
  • @PrepareForTest({Calculator.class}). This annotation describe the class which static methods will be mocked using mockStatic method.
In conclusion, PowerMock is a powerful testing framework which implements record/replay/verify phases in a similar manner as mocker. For more details, please visit: http://code.google.com/p/powermock/w/list

Niciun comentariu:

Trimiteți un comentariu