Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock static methods from multiple class using PowerMock

I know how to mock static methods from a class using PowerMock.
But I want to mock static methods from multiple classes in a test class using JUnit and PowerMock.

Can anyone tell me is it possible to do this and how to do it?

like image 916
Newbie Avatar asked Apr 26 '12 05:04

Newbie


People also ask

How do you mock with PowerMock?

Step 1: Create a class that contains a private method. We have created class with the name Utility and defined a private method and a public method (that returns the object of private method). Step 2: Create a JUnit test case named PowerMock_test for testing purpose.

Can we mock static methods?

Since static method belongs to the class, there is no way in Mockito to mock static methods. However, we can use PowerMock along with Mockito framework to mock static methods.

Why PowerMock is not recommended?

Power Mock gives you access to mock static methods, constructors etc. and this means that your code is not following best programming principles. Power Mock should be used in legacy applications where you cannot change the code which has been given to you.


2 Answers

Just do @PrepareForTest({Class1.class,Class2.class}) for multiple classes.

like image 170
artbristol Avatar answered Sep 20 '22 15:09

artbristol


@Test  @PrepareForTest({Class1.class, Class2.class})  public final void handleScript() throws Exception {     PowerMockito.mockStatic(Class1.class);     PowerMockito.mockStatic(Class2.class); 

etc...

like image 36
arush436 Avatar answered Sep 17 '22 15:09

arush436