Моделирование статических методов Краткая сводка
Use the @RunWith(PowerMockRunner.class) annotation at the class-level of the test case.
Use the @PrepareForTest(ClassThatContainsStaticMethod.class) annotation at the class-level of the test case.
Use PowerMock.mockStatic(ClassThatContainsStaticMethod.class) to mock all methods of this class.
Use PowerMock.replay(ClassThatContainsStaticMethod.class) to change the class to replay mode.
Use PowerMock.verify(ClassThatContainsStaticMethod.class) to change the class to verify mode.
Пример Для моделирования статического метода в PowerMock требуется использование метода «mockStatic» в PowerMock.Допустим, у вас есть класс ServiceRegistrator с методом registerService, который выглядит следующим образом:
public long registerService(Object service) {
final long id = IdGenerator.generateNewId();
serviceRegistrations.put(id, service);
return id;
}
Интересным моментом здесь является статический вызов метода IdGenerator.generateNewId (), который мы хотели бы смоделировать,IdGenerator - это вспомогательный класс, который просто генерирует новый идентификатор для службы.Это выглядит следующим образом:
public class IdGenerator {
/**
* @return A new ID based on the current time.
*/
public static long generateNewId() {
return System.currentTimeMillis();
}
}
С PowerMock можно ожидать вызова IdGenerator.generateNewId () так же, как и с любым другим методом, использующим EasyMock, после того как вы сказали PowerMock подготовить класс IdGenerator длятестирование.Вы делаете это, добавляя аннотацию к уровню теста.Это просто сделать с помощью @PrepareForTest (IdGenerator.class).Вы также должны указать JUnit выполнить тест с использованием PowerMock, который выполняется с помощью @RunWith (PowerMockRunner.class).Без этих двух аннотаций тест не пройден.
Реальный тест на самом деле довольно прост:
@Test
public void testRegisterService() throws Exception {
long expectedId = 42;
// We create a new instance of test class under test as usually.
ServiceRegistartor tested = new ServiceRegistartor();
// This is the way to tell PowerMock to mock all static methods of a
// given class
mockStatic(IdGenerator.class);
/*
* The static method call to IdGenerator.generateNewId() expectation.
* This is why we need PowerMock.
*/
expect(IdGenerator.generateNewId()).andReturn(expectedId);
// Note how we replay the class, not the instance!
replay(IdGenerator.class);
long actualId = tested.registerService(new Object());
// Note how we verify the class, not the instance!
verify(IdGenerator.class);
// Assert that the ID is correct
assertEquals(expectedId, actualId);
}
Обратите внимание, что вы можете макетировать статические методы в классе, даже если класс является окончательным.Метод также может быть окончательным.Чтобы смоделировать только определенные статические методы класса, обратитесь к разделу частичной имитации в документации.
Ссылка: powermock wiki