34

What does the annotation @PrepareForTest in PowerMockito really mean?

What should be placed there apart of classes which have static methods?

GhostCat
  • 137,827
  • 25
  • 176
  • 248
Ernesto
  • 950
  • 1
  • 14
  • 31
  • 3
    Check docs here https://github.com/powermock/powermock/wiki/Mockito – Nkosi Jun 03 '19 at 15:13
  • @GhostCat kinda, imo you need to pass the ClassUnderTesting.class there also if you want to mock private methods invokings of this class, also additionally you need to put Spy above the InjectMocks which is also above the ClassUnderTesting initialization. – Ernesto Jun 04 '19 at 09:15

1 Answers1

58

That annotation tells PowerMock(ito) that the listed classes will need to be manipulated on the byte code level.

You need to "prepare for test" all these classes X of which you want to

  • mock a static method (on X)
  • gain control over calls to new() used in another class X
  • gain control over private methods (which you do using a spy and
    PowerMockito.when(spy, "privateMethodNameAsString").then...

In other words:

  • To mock X.doStatic(), you have to prepare the class X.
  • To control new Y(...), you have to prepare the class X that contains that new statement.
Ahmed Nabil
  • 17,392
  • 11
  • 61
  • 88
GhostCat
  • 137,827
  • 25
  • 176
  • 248
  • 3
    Just to add to that, it also lets you do things like mock an Enum. – saran3h Jul 03 '20 at 03:11
  • Yes, but that is again something I dislike doing. If I need to "mock" such things, my enums implement some interface I can mock (without PowerMock). – GhostCat Jul 03 '20 at 07:17