- mocking static functions/methods
- mocking private functions/methods
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.
Niciun comentariu:
Trimiteți un comentariu