kandi background
Explore Kits

powermock | Java framework | Mock library

 by   powermock Java Version: powermock-2.0.9 License: Apache-2.0

 by   powermock Java Version: powermock-2.0.9 License: Apache-2.0

Download this library from

kandi X-RAY | powermock Summary

powermock is a Java library typically used in Testing, Mock applications. powermock has no bugs, it has no vulnerabilities, it has build file available, it has a Permissive License and it has high support. You can download it from GitHub, Maven.
Please, read the guideline for a new contributor before start.
Support
Support
Quality
Quality
Security
Security
License
License
Reuse
Reuse

kandi-support Support

  • powermock has a highly active ecosystem.
  • It has 3751 star(s) with 555 fork(s). There are 173 watchers for this library.
  • It had no major release in the last 12 months.
  • There are 413 open issues and 537 have been closed. On average issues are closed in 228 days. There are 15 open pull requests and 0 closed requests.
  • It has a negative sentiment in the developer community.
  • The latest version of powermock is powermock-2.0.9
powermock Support
Best in #Mock
Average in #Mock
powermock Support
Best in #Mock
Average in #Mock

quality kandi Quality

  • powermock has 0 bugs and 0 code smells.
powermock Quality
Best in #Mock
Average in #Mock
powermock Quality
Best in #Mock
Average in #Mock

securitySecurity

  • powermock has no vulnerabilities reported, and its dependent libraries have no vulnerabilities reported.
  • powermock code analysis shows 0 unresolved vulnerabilities.
  • There are 0 security hotspots that need review.
powermock Security
Best in #Mock
Average in #Mock
powermock Security
Best in #Mock
Average in #Mock

license License

  • powermock is licensed under the Apache-2.0 License. This license is Permissive.
  • Permissive licenses have the least restrictions, and you can use them in most projects.
powermock License
Best in #Mock
Average in #Mock
powermock License
Best in #Mock
Average in #Mock

buildReuse

  • powermock releases are available to install and integrate.
  • Deployable package is available in Maven.
  • Build file is available. You can build the component from source.
  • powermock saves you 19302 person hours of effort in developing the same functionality from scratch.
  • It has 38094 lines of code, 4001 functions and 946 files.
  • It has low code complexity. Code complexity directly impacts maintainability of the code.
powermock Reuse
Best in #Mock
Average in #Mock
powermock Reuse
Best in #Mock
Average in #Mock
Top functions reviewed by kandi - BETA

kandi has reviewed powermock and discovered the below as its top functions. This is intended to give you an instant insight into powermock implemented functionality, and help decide if they suit your requirements.

  • Finds a method or throws an exception if not found .
  • Executes a command on the target VM .
  • Compares two versions .
  • Create a defer constructor .
  • Reads the class .
  • Reset the given objects .
  • Checks whether the given text matches the pattern .
  • Update the error message based on the verifyNoInteractionsMessage
  • Create a delegate runner for the given test class .
  • Create a concrete sub class .

powermock Key Features

PowerMock is a Java framework that allows you to unit test code normally regarded as untestable.

Java Mocking a private final field or response form RestHighLevelClient

copy iconCopydownload iconDownload
    @Test
    public void testgetAllMoviesListResult() {
        ESEntity elasticSearchEntity = new ESearchEntity();
        SearchSourceBuilder sourceBuilder = elasticSearchEntity.createElasticSearchQueryForGetAllMovieList();
        when(mockElasticSearchEntity.createElasticSearchQueryForGetAllMovieList()).thenReturn(sourceBuilder);

        String esReponse = "";
        JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new JsonFactory().createParser(esResponse));
        SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);

        RestHighLevelClient mockRestHighLevelClient = mock(RestHighLevelClient.class);
        when(mockRestHighLevelClient.search(any(), any())).thenReturn(searchResponse);
        
        try (MockedStatic<OpenSearchRestHighLevelClient> openSearchRestHighLevelClient = mockStatic(OpenSearchRestHighLevelClient.class)) {
            openSearchRestHighLevelClient.when(OpenSearchRestHighLevelClient::getRestHighLevelClient).thenReturn(mockRestHighLevelClient);
            String actualResponse = new EntityService().getAllMoviesListResult("someIndex");
            assertEquals(expectedResponse, actualResponse);
        }

    }

Unable to mock System class static method using PowerMockito

copy iconCopydownload iconDownload
@RunWith(PowerMockRunner.class)
@PrepareForTest(SCUtil.class)
public class SCUtilTest {

    private SCUtil scUtil = new SCUtil();

    @Test(expected = ServiceException.class)
    public void testCreateSC_Exception () throws UnknownHostException {
        PowerMockito.mockStatic(InetAddress.class);
        PowerMockito.when(InetAddress.getLocalHost()).thenThrow(new UnknownHostException("test"));
        scUtil.createSC();
    }
}

Why does ExceptionInInitializerError occur when invoking HtmlCompat in an Android unit test using Robolectric?

copy iconCopydownload iconDownload
    testOptions {
        unitTests {
            includeAndroidResources = true
        }
    }

NotAMockException exception when trying to verify a static method with Powermockito

copy iconCopydownload iconDownload
public class SomeClass {
  public static String doSomething(int x) { ... }
}
public class MyClass {
  public void someMethod() {
    String xyz = SomeClass.doSomething(123);
    ...
  }
}
public class MyDelegator {
  public String doSomething(int x) { 
    return SomeClass.doSomething(x);
  } 
}
public class MyClass {
  private final MyDelegator myDelegator;

  public MyClass(MyDelegator myDelegator) { this.myDelegator = myDelegator; }

  public void someMethod() {
    String xyz = myDelegator.doSomething(123);
    ...
  }
}
-----------------------
public class SomeClass {
  public static String doSomething(int x) { ... }
}
public class MyClass {
  public void someMethod() {
    String xyz = SomeClass.doSomething(123);
    ...
  }
}
public class MyDelegator {
  public String doSomething(int x) { 
    return SomeClass.doSomething(x);
  } 
}
public class MyClass {
  private final MyDelegator myDelegator;

  public MyClass(MyDelegator myDelegator) { this.myDelegator = myDelegator; }

  public void someMethod() {
    String xyz = myDelegator.doSomething(123);
    ...
  }
}
-----------------------
public class SomeClass {
  public static String doSomething(int x) { ... }
}
public class MyClass {
  public void someMethod() {
    String xyz = SomeClass.doSomething(123);
    ...
  }
}
public class MyDelegator {
  public String doSomething(int x) { 
    return SomeClass.doSomething(x);
  } 
}
public class MyClass {
  private final MyDelegator myDelegator;

  public MyClass(MyDelegator myDelegator) { this.myDelegator = myDelegator; }

  public void someMethod() {
    String xyz = myDelegator.doSomething(123);
    ...
  }
}
-----------------------
public class SomeClass {
  public static String doSomething(int x) { ... }
}
public class MyClass {
  public void someMethod() {
    String xyz = SomeClass.doSomething(123);
    ...
  }
}
public class MyDelegator {
  public String doSomething(int x) { 
    return SomeClass.doSomething(x);
  } 
}
public class MyClass {
  private final MyDelegator myDelegator;

  public MyClass(MyDelegator myDelegator) { this.myDelegator = myDelegator; }

  public void someMethod() {
    String xyz = myDelegator.doSomething(123);
    ...
  }
}
-----------------------
    try (MockedStatic<Files> filesMock = Mockito.mockStatic(Files.class)) {
        filesMock.when(() -> Files.copy(any(Path.class), any(OutputStream.class))).thenReturn(1L);
     
        // Call logic
    }
    private MockedStatic<Files> filesMock;

    @Before
    public void init() {
        filesMock = org.mockito.Mockito.mockStatic(Files.class);
    }

    @After
    public void teardown() {
        filesMock.close();
    }
    
    @Test
    void test() {
        filesMock.when(() -> Files.copy(any(Path.class), any(OutputStream.class))).thenReturn(1L);
    }
-----------------------
    try (MockedStatic<Files> filesMock = Mockito.mockStatic(Files.class)) {
        filesMock.when(() -> Files.copy(any(Path.class), any(OutputStream.class))).thenReturn(1L);
     
        // Call logic
    }
    private MockedStatic<Files> filesMock;

    @Before
    public void init() {
        filesMock = org.mockito.Mockito.mockStatic(Files.class);
    }

    @After
    public void teardown() {
        filesMock.close();
    }
    
    @Test
    void test() {
        filesMock.when(() -> Files.copy(any(Path.class), any(OutputStream.class))).thenReturn(1L);
    }

Getting warning SLF4J :Class path contains multiple SLF4J bindings

copy iconCopydownload iconDownload
SLF4J: Found binding in [jar:file:/Users/macuser/.m2/repository/ch/qos/logback/logback-classic/1.2.10/logback-classic-1.2.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/macuser/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.17.1/log4j-slf4j-impl-2.17.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
mvn dependency:tree '-Dincludes=ch.qos.logback:logback-classic,org.apache.logging.log4j:log4j-slf4j-impl'
-----------------------
SLF4J: Found binding in [jar:file:/Users/macuser/.m2/repository/ch/qos/logback/logback-classic/1.2.10/logback-classic-1.2.10.jar!/org/slf4j/impl/StaticLoggerBinder.class]
SLF4J: Found binding in [jar:file:/Users/macuser/.m2/repository/org/apache/logging/log4j/log4j-slf4j-impl/2.17.1/log4j-slf4j-impl-2.17.1.jar!/org/slf4j/impl/StaticLoggerBinder.class]
mvn dependency:tree '-Dincludes=ch.qos.logback:logback-classic,org.apache.logging.log4j:log4j-slf4j-impl'

Set value for private final static inlined variable using Mockito

copy iconCopydownload iconDownload
private static void setFinalStatic(Field field, Object newValue) throws Exception {
   Field field = ClassWhereToMockStaticFinalVar.class.getDeclaredField("FieldName");   
   field.setAccessible(true);
 
   // remove final modifier from field
   Field modifiersField = Field.class.getDeclaredField("modifiers");
   modifiersField.setAccessible(true);
   modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
   field.set(null, newValue);
}

Error inflating ViewBinding in test class : Binary XML file line #38: Binary XML file line #38: Error inflating class &lt;unknown&gt;

copy iconCopydownload iconDownload
public final class ActivityMainBinding implements ViewBinding {
  @NonNull
  private final ConstraintLayout rootView;

  @NonNull
  public final Button getText;

  @NonNull
  public final ProgressBar progress;

  @NonNull
  public final TextView text;

  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button getText,
      @NonNull ProgressBar progress, @NonNull TextView text) {
    this.rootView = rootView;
    this.getText = getText;
    this.progress = progress;
    this.text = text;
  }

  @Override
  @NonNull
  public ConstraintLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.get_text;
      Button getText = ViewBindings.findChildViewById(rootView, id);
      if (getText == null) {
        break missingId;
      }

      id = R.id.progress;
      ProgressBar progress = ViewBindings.findChildViewById(rootView, id);
      if (progress == null) {
        break missingId;
      }

      id = R.id.text;
      TextView text = ViewBindings.findChildViewById(rootView, id);
      if (text == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, getText, progress, text);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}
@Before
fun setUp() {
    // return the mock root from the mock inflater
    doReturn(mMockConvertView).`when`(mMockInflater).inflate(R.layout.my_layout, mMockViewGroup, false)
    
    // extra mocks to handle findChildViewById
    doReturn(1).`when`(mMockConvertView).childCount
    doReturn(mMockConvertView).`when`(mMockConvertView).getChildAt(0)

    // Return the mocked views
    doReturn(mMockText).`when`(mMockConvertView).findViewById<View>(R.id.text)
    doReturn(mMockButton).`when`(mMockConvertView).findViewById<View>(R.id.get_text)
    doReturn(mMockProgBar).`when`(mMockConvertView).findViewById<View>(R.id.progress)
}
@Nullable
public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
    if (!(rootView instanceof ViewGroup)) {
        return null;
    }
    final ViewGroup rootViewGroup = (ViewGroup) rootView;
    final int childCount = rootViewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final T view = rootViewGroup.getChildAt(i).findViewById(id);
        if (view != null) {
            return view;
        }
    }
    return null;
}
val binding = ActivityMainBinding.inflate(mMockInflater, mMockViewGroup, false)
-----------------------
public final class ActivityMainBinding implements ViewBinding {
  @NonNull
  private final ConstraintLayout rootView;

  @NonNull
  public final Button getText;

  @NonNull
  public final ProgressBar progress;

  @NonNull
  public final TextView text;

  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button getText,
      @NonNull ProgressBar progress, @NonNull TextView text) {
    this.rootView = rootView;
    this.getText = getText;
    this.progress = progress;
    this.text = text;
  }

  @Override
  @NonNull
  public ConstraintLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.get_text;
      Button getText = ViewBindings.findChildViewById(rootView, id);
      if (getText == null) {
        break missingId;
      }

      id = R.id.progress;
      ProgressBar progress = ViewBindings.findChildViewById(rootView, id);
      if (progress == null) {
        break missingId;
      }

      id = R.id.text;
      TextView text = ViewBindings.findChildViewById(rootView, id);
      if (text == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, getText, progress, text);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}
@Before
fun setUp() {
    // return the mock root from the mock inflater
    doReturn(mMockConvertView).`when`(mMockInflater).inflate(R.layout.my_layout, mMockViewGroup, false)
    
    // extra mocks to handle findChildViewById
    doReturn(1).`when`(mMockConvertView).childCount
    doReturn(mMockConvertView).`when`(mMockConvertView).getChildAt(0)

    // Return the mocked views
    doReturn(mMockText).`when`(mMockConvertView).findViewById<View>(R.id.text)
    doReturn(mMockButton).`when`(mMockConvertView).findViewById<View>(R.id.get_text)
    doReturn(mMockProgBar).`when`(mMockConvertView).findViewById<View>(R.id.progress)
}
@Nullable
public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
    if (!(rootView instanceof ViewGroup)) {
        return null;
    }
    final ViewGroup rootViewGroup = (ViewGroup) rootView;
    final int childCount = rootViewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final T view = rootViewGroup.getChildAt(i).findViewById(id);
        if (view != null) {
            return view;
        }
    }
    return null;
}
val binding = ActivityMainBinding.inflate(mMockInflater, mMockViewGroup, false)
-----------------------
public final class ActivityMainBinding implements ViewBinding {
  @NonNull
  private final ConstraintLayout rootView;

  @NonNull
  public final Button getText;

  @NonNull
  public final ProgressBar progress;

  @NonNull
  public final TextView text;

  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button getText,
      @NonNull ProgressBar progress, @NonNull TextView text) {
    this.rootView = rootView;
    this.getText = getText;
    this.progress = progress;
    this.text = text;
  }

  @Override
  @NonNull
  public ConstraintLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.get_text;
      Button getText = ViewBindings.findChildViewById(rootView, id);
      if (getText == null) {
        break missingId;
      }

      id = R.id.progress;
      ProgressBar progress = ViewBindings.findChildViewById(rootView, id);
      if (progress == null) {
        break missingId;
      }

      id = R.id.text;
      TextView text = ViewBindings.findChildViewById(rootView, id);
      if (text == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, getText, progress, text);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}
@Before
fun setUp() {
    // return the mock root from the mock inflater
    doReturn(mMockConvertView).`when`(mMockInflater).inflate(R.layout.my_layout, mMockViewGroup, false)
    
    // extra mocks to handle findChildViewById
    doReturn(1).`when`(mMockConvertView).childCount
    doReturn(mMockConvertView).`when`(mMockConvertView).getChildAt(0)

    // Return the mocked views
    doReturn(mMockText).`when`(mMockConvertView).findViewById<View>(R.id.text)
    doReturn(mMockButton).`when`(mMockConvertView).findViewById<View>(R.id.get_text)
    doReturn(mMockProgBar).`when`(mMockConvertView).findViewById<View>(R.id.progress)
}
@Nullable
public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
    if (!(rootView instanceof ViewGroup)) {
        return null;
    }
    final ViewGroup rootViewGroup = (ViewGroup) rootView;
    final int childCount = rootViewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final T view = rootViewGroup.getChildAt(i).findViewById(id);
        if (view != null) {
            return view;
        }
    }
    return null;
}
val binding = ActivityMainBinding.inflate(mMockInflater, mMockViewGroup, false)
-----------------------
public final class ActivityMainBinding implements ViewBinding {
  @NonNull
  private final ConstraintLayout rootView;

  @NonNull
  public final Button getText;

  @NonNull
  public final ProgressBar progress;

  @NonNull
  public final TextView text;

  private ActivityMainBinding(@NonNull ConstraintLayout rootView, @NonNull Button getText,
      @NonNull ProgressBar progress, @NonNull TextView text) {
    this.rootView = rootView;
    this.getText = getText;
    this.progress = progress;
    this.text = text;
  }

  @Override
  @NonNull
  public ConstraintLayout getRoot() {
    return rootView;
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater) {
    return inflate(inflater, null, false);
  }

  @NonNull
  public static ActivityMainBinding inflate(@NonNull LayoutInflater inflater,
      @Nullable ViewGroup parent, boolean attachToParent) {
    View root = inflater.inflate(R.layout.activity_main, parent, false);
    if (attachToParent) {
      parent.addView(root);
    }
    return bind(root);
  }

  @NonNull
  public static ActivityMainBinding bind(@NonNull View rootView) {
    // The body of this method is generated in a way you would not otherwise write.
    // This is done to optimize the compiled bytecode for size and performance.
    int id;
    missingId: {
      id = R.id.get_text;
      Button getText = ViewBindings.findChildViewById(rootView, id);
      if (getText == null) {
        break missingId;
      }

      id = R.id.progress;
      ProgressBar progress = ViewBindings.findChildViewById(rootView, id);
      if (progress == null) {
        break missingId;
      }

      id = R.id.text;
      TextView text = ViewBindings.findChildViewById(rootView, id);
      if (text == null) {
        break missingId;
      }

      return new ActivityMainBinding((ConstraintLayout) rootView, getText, progress, text);
    }
    String missingId = rootView.getResources().getResourceName(id);
    throw new NullPointerException("Missing required view with ID: ".concat(missingId));
  }
}
@Before
fun setUp() {
    // return the mock root from the mock inflater
    doReturn(mMockConvertView).`when`(mMockInflater).inflate(R.layout.my_layout, mMockViewGroup, false)
    
    // extra mocks to handle findChildViewById
    doReturn(1).`when`(mMockConvertView).childCount
    doReturn(mMockConvertView).`when`(mMockConvertView).getChildAt(0)

    // Return the mocked views
    doReturn(mMockText).`when`(mMockConvertView).findViewById<View>(R.id.text)
    doReturn(mMockButton).`when`(mMockConvertView).findViewById<View>(R.id.get_text)
    doReturn(mMockProgBar).`when`(mMockConvertView).findViewById<View>(R.id.progress)
}
@Nullable
public static <T extends View> T findChildViewById(View rootView, @IdRes int id) {
    if (!(rootView instanceof ViewGroup)) {
        return null;
    }
    final ViewGroup rootViewGroup = (ViewGroup) rootView;
    final int childCount = rootViewGroup.getChildCount();
    for (int i = 0; i < childCount; i++) {
        final T view = rootViewGroup.getChildAt(i).findViewById(id);
        if (view != null) {
            return view;
        }
    }
    return null;
}
val binding = ActivityMainBinding.inflate(mMockInflater, mMockViewGroup, false)

Fail to restTemplate create with @PowerMockIgnore in powermock

copy iconCopydownload iconDownload
com.sun.org.apache.xalan.internal.xsltc.trax.*
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.powermock.api.mockito.PowerMockito.*;

import java.io.File;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import lombok.AllArgsConstructor;
import lombok.Data;


@SpringBootTest
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest(PowerMockTarget.class)
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "javax.xml.transform.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xalan.internal.xsltc.trax.*"})
public class PowerMockTest {

    @Test
    public void mockStaticMethod() throws Exception {
        File fileMock = mock(File.class);
        when(fileMock.exists()).thenReturn(true);

        whenNew(File.class.getConstructor(String.class)).withArguments(anyString()).thenReturn(fileMock);
        
        PowerMockTarget target = new PowerMockTarget();
        assertEquals(target.isFileExist(), true);

        assertEquals("My bean message", message.getContent());
    }
}

@Data
@AllArgsConstructor
class MessageForTest{
    private long id;
    private String content;
    
}


@Data
@AllArgsConstructor
class MessageForTest{
    private long id;
    private String content;
    
}
import java.io.File;

public class PowerMockTarget {

    public boolean isFileExist() {
    
        if(!new File("filename").exists()) {
          throw new RuntimeException();
        }
        return true;
    }
}
-----------------------
com.sun.org.apache.xalan.internal.xsltc.trax.*
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.powermock.api.mockito.PowerMockito.*;

import java.io.File;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import lombok.AllArgsConstructor;
import lombok.Data;


@SpringBootTest
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest(PowerMockTarget.class)
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "javax.xml.transform.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xalan.internal.xsltc.trax.*"})
public class PowerMockTest {

    @Test
    public void mockStaticMethod() throws Exception {
        File fileMock = mock(File.class);
        when(fileMock.exists()).thenReturn(true);

        whenNew(File.class.getConstructor(String.class)).withArguments(anyString()).thenReturn(fileMock);
        
        PowerMockTarget target = new PowerMockTarget();
        assertEquals(target.isFileExist(), true);

        assertEquals("My bean message", message.getContent());
    }
}

@Data
@AllArgsConstructor
class MessageForTest{
    private long id;
    private String content;
    
}


@Data
@AllArgsConstructor
class MessageForTest{
    private long id;
    private String content;
    
}
import java.io.File;

public class PowerMockTarget {

    public boolean isFileExist() {
    
        if(!new File("filename").exists()) {
          throw new RuntimeException();
        }
        return true;
    }
}
-----------------------
com.sun.org.apache.xalan.internal.xsltc.trax.*
import static org.junit.Assert.*;
import static org.mockito.ArgumentMatchers.*;
import static org.powermock.api.mockito.PowerMockito.*;

import java.io.File;

import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.powermock.modules.junit4.PowerMockRunnerDelegate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.stereotype.Component;
import org.springframework.test.context.junit4.SpringRunner;

import lombok.AllArgsConstructor;
import lombok.Data;


@SpringBootTest
@RunWith(PowerMockRunner.class)
@PowerMockRunnerDelegate(SpringRunner.class)
@PrepareForTest(PowerMockTarget.class)
@PowerMockIgnore({"com.sun.org.apache.xerces.*", "javax.xml.*", "javax.xml.transform.*", "org.xml.*", "javax.management.*", "javax.net.ssl.*", "com.sun.org.apache.xalan.internal.xsltc.trax.*"})
public class PowerMockTest {

    @Test
    public void mockStaticMethod() throws Exception {
        File fileMock = mock(File.class);
        when(fileMock.exists()).thenReturn(true);

        whenNew(File.class.getConstructor(String.class)).withArguments(anyString()).thenReturn(fileMock);
        
        PowerMockTarget target = new PowerMockTarget();
        assertEquals(target.isFileExist(), true);

        assertEquals("My bean message", message.getContent());
    }
}

@Data
@AllArgsConstructor
class MessageForTest{
    private long id;
    private String content;
    
}


@Data
@AllArgsConstructor
class MessageForTest{
    private long id;
    private String content;
    
}
import java.io.File;

public class PowerMockTarget {

    public boolean isFileExist() {
    
        if(!new File("filename").exists()) {
          throw new RuntimeException();
        }
        return true;
    }
}

PowerMockito returns null when mocking private method for testing public method

copy iconCopydownload iconDownload
@RunWith(PowerMockRunner.class)
@PrepareForTest(TextManager.class)
public class TextManagerTest {

  @Test
  public void checkIfConcatenationWorks() throws Exception {
    // Arrange
    TextManager textmanager = PowerMockito.spy(new TextManager());
    PowerMockito.doReturn("someText").when(textmanager,"concatenateTwoString"
    , Mockito.anyString()
    , Mockito.anyString());

    // Act
    String text = textmanager.concatenate("ji","bo");

    // Assert
    assertThat(text).isEqualTo("jibo");
  }
}
-----------------------
 <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.8.1</version>
    </dependency>


    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    import org.junit.Assert;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(TextManager.class)
    @RunWith(PowerMockRunner.class)
    public class TextManagerTest {
    
        @org.junit.Test  //Test using Junit4
        public void checkIfConcatenationWorksWithJunit4() throws Exception {
            TextManager textmanager = PowerMockito.spy(new TextManager());
            PowerMockito.doReturn("jibo").when(textmanager, "concatenateTwoString", Mockito.anyString(), Mockito.anyString());
            String text = textmanager.concatenate("ji", "bo");
            Assert.assertEquals(text,"jibo");
        }
    
        @Test  //Test using Junit5
        public void checkIfConcatenationWorksWithJunit5() {
            Assertions.assertEquals("text","jibo");
        }
    }
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
-----------------------
 <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.8.1</version>
    </dependency>


    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    import org.junit.Assert;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(TextManager.class)
    @RunWith(PowerMockRunner.class)
    public class TextManagerTest {
    
        @org.junit.Test  //Test using Junit4
        public void checkIfConcatenationWorksWithJunit4() throws Exception {
            TextManager textmanager = PowerMockito.spy(new TextManager());
            PowerMockito.doReturn("jibo").when(textmanager, "concatenateTwoString", Mockito.anyString(), Mockito.anyString());
            String text = textmanager.concatenate("ji", "bo");
            Assert.assertEquals(text,"jibo");
        }
    
        @Test  //Test using Junit5
        public void checkIfConcatenationWorksWithJunit5() {
            Assertions.assertEquals("text","jibo");
        }
    }
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>
-----------------------
 <dependency>
        <groupId>org.junit.jupiter</groupId>
        <artifactId>junit-jupiter-engine</artifactId>
        <version>5.8.1</version>
    </dependency>
    <dependency>
        <groupId>org.junit.vintage</groupId>
        <artifactId>junit-vintage-engine</artifactId>
        <version>5.8.1</version>
    </dependency>


    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-module-junit4</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.powermock</groupId>
        <artifactId>powermock-api-mockito2</artifactId>
        <version>2.0.9</version>
        <scope>test</scope>
    </dependency>
    import org.junit.Assert;
    import org.junit.jupiter.api.Assertions;
    import org.junit.jupiter.api.Test;
    import org.junit.runner.RunWith;
    import org.mockito.Mockito;
    import org.powermock.api.mockito.PowerMockito;
    import org.powermock.core.classloader.annotations.PrepareForTest;
    import org.powermock.modules.junit4.PowerMockRunner;
    
    @PrepareForTest(TextManager.class)
    @RunWith(PowerMockRunner.class)
    public class TextManagerTest {
    
        @org.junit.Test  //Test using Junit4
        public void checkIfConcatenationWorksWithJunit4() throws Exception {
            TextManager textmanager = PowerMockito.spy(new TextManager());
            PowerMockito.doReturn("jibo").when(textmanager, "concatenateTwoString", Mockito.anyString(), Mockito.anyString());
            String text = textmanager.concatenate("ji", "bo");
            Assert.assertEquals(text,"jibo");
        }
    
        @Test  //Test using Junit5
        public void checkIfConcatenationWorksWithJunit5() {
            Assertions.assertEquals("text","jibo");
        }
    }
   <build>
        <plugins>
            <plugin>
                <artifactId>maven-surefire-plugin</artifactId>
                <version>2.22.2</version>
            </plugin>
        </plugins>
    </build>

Mock a method coming from parent class to return a mocked data

copy iconCopydownload iconDownload
@RunWith(PowerMockRunner.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService = new OfferService();

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        PowerMockito.when(offerService, "getHttpEntity", "www.example.com")
            .thenReturn(entity);

        PowerMockito.when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}
 
@ExtendWith(MockitoExtension.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        when(ReflectionTestUtils.invokeMethod(offerService, "getHttpEntity", "www.example.com"))
                .thenReturn(entity);

        when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}
-----------------------
@RunWith(PowerMockRunner.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService = new OfferService();

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        PowerMockito.when(offerService, "getHttpEntity", "www.example.com")
            .thenReturn(entity);

        PowerMockito.when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}
 
@ExtendWith(MockitoExtension.class)
public class OfferServiceTest {

    @Spy
    @InjectMocks
    private OfferService offerService;

    @Mock
    private RestTemplate restTemplate;

    @Mock
    private HttpEntity<Object> entity;


    @Test
    public void test() {
        when(ReflectionTestUtils.invokeMethod(offerService, "getHttpEntity", "www.example.com"))
                .thenReturn(entity);

        when(restTemplate.exchange(anyString(), any(), any(), any()))
                .thenReturn(something);

        assertEquals(someObject, offerService.get());
    }
}

Community Discussions

Trending Discussions on powermock
  • Java Mocking a private final field or response form RestHighLevelClient
  • Unable to mock System class static method using PowerMockito
  • Why does ExceptionInInitializerError occur when invoking HtmlCompat in an Android unit test using Robolectric?
  • NotAMockException exception when trying to verify a static method with Powermockito
  • Getting warning SLF4J :Class path contains multiple SLF4J bindings
  • Why is my android studio kotlin plugin version in different format than my co-workers?
  • Set value for private final static inlined variable using Mockito
  • Error inflating ViewBinding in test class : Binary XML file line #38: Binary XML file line #38: Error inflating class &lt;unknown&gt;
  • Fail to restTemplate create with @PowerMockIgnore in powermock
  • java.lang.IllegalArgumentException: Cannot instantiate interface org.springframework.context.ApplicationListener
Trending Discussions on powermock

QUESTION

Java Mocking a private final field or response form RestHighLevelClient

Asked 2022-Mar-31 at 06:09

I am trying to write a testcase for the below method and I need to mock the response obtained from the elastic search db.

@Inject
ESEntity mockElasticSearchEntity;
private final RestHighLevelClient restHighLevelClient = OpenSearchRestHighLevelClient.getRestHighLevelClient();

public String getAllMoviesListResult(String index){
    SourceBuilder sourceBuilder = entity.createElasticSearchQueryForGetAllMovieList();
    SearchRequest searchRequest = new SearchRequest(index);
    searchRequest.source(sourceBuilder);

    SearchResponse searchResponse = restHighLevelClient.search(searchRequest,RequestOption.DEFAULT);
    return searchResponse.getHits().get(0);
}

I have written the below test case: Instead of getting the mock response, the code flows to RestHighLevelClient class and returns NullPointException.

@InjectMock
ESEntity mockElasticSearchEntity;

@Test
public void testgetAllMoviesListResult(){
    ESEntity elasticSearchEntity = new ESearchEntity();
    SearchSourceBuilder sourceBuilder = elasticSearchEntity.createElasticSearchQueryForGetAllMovieList();
    when(mockElasticSearchEntity.createElasticSearchQueryForGetAllMovieList()).thenReturn(sourceBuilder);
    
    String esReponse ="";
    JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new JsonFactory().createParser(esResponse));
    SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);

    RestHighLevelClient mockRestHighLevelClient = mock(RestHighLevelClient.class);
    when(mockRestHighLevelClient.search(any(),any())).thenReturn(searchResponse);
    
    String actualResponse = new EntityService().getAllMoviesListResult("someIndex");
    
}

I searched for similar issues but that required the use of PowerMock, which is not supported by the framework which I am currently using.

Update

public class OpenSearchRestHighLevelClient {

    private static RestHighLevelClient restHighLevelClient = null;
    
    public static RestHighLevelClient getRestHighLevelClient() {     
        //singleton implementation on receiving the RestHighLevelClient.
        if(restHighLevelClient==null) {
            restHighLevelClient = createRestHighLevelClient();
        }
        return restHighLevelClient;
    }
    
    public static RestHighLevelClient createRestHighLevelClient(){
        //logic to create RestHighLevelClient
    }
}

ANSWER

Answered 2022-Mar-31 at 06:09

There's a workaround I can think of, you can mock the static method of object creation of RestHighLevelClient using mock static(checkout) https://mvnrepository.com/artifact/org.mockito/mockito-inline

I am using Gradle testImplementation 'org.mockito:mockito-inline:3.4.6' This worked for me, let me know

    @Test
    public void testgetAllMoviesListResult() {
        ESEntity elasticSearchEntity = new ESearchEntity();
        SearchSourceBuilder sourceBuilder = elasticSearchEntity.createElasticSearchQueryForGetAllMovieList();
        when(mockElasticSearchEntity.createElasticSearchQueryForGetAllMovieList()).thenReturn(sourceBuilder);

        String esReponse = "";
        JsonXContentParser xContentParser = new JsonXContentParser(NamedXContentRegistry.EMPTY, DeprecationHandler.THROW_UNSUPPORTED_OPERATION, new JsonFactory().createParser(esResponse));
        SearchResponse searchResponse = SearchResponse.fromXContent(xContentParser);

        RestHighLevelClient mockRestHighLevelClient = mock(RestHighLevelClient.class);
        when(mockRestHighLevelClient.search(any(), any())).thenReturn(searchResponse);
        
        try (MockedStatic<OpenSearchRestHighLevelClient> openSearchRestHighLevelClient = mockStatic(OpenSearchRestHighLevelClient.class)) {
            openSearchRestHighLevelClient.when(OpenSearchRestHighLevelClient::getRestHighLevelClient).thenReturn(mockRestHighLevelClient);
            String actualResponse = new EntityService().getAllMoviesListResult("someIndex");
            assertEquals(expectedResponse, actualResponse);
        }

    }

Source https://stackoverflow.com/questions/71686750

Community Discussions, Code Snippets contain sources that include Stack Exchange Network

Vulnerabilities

No vulnerabilities reported

Install powermock

You can download it from GitHub, Maven.
You can use powermock like any standard Java library. Please include the the jar files in your classpath. You can also use any IDE and you can run and debug the powermock component as you would do with any other Java program. Best practice is to use a build tool that supports dependency management such as Maven or Gradle. For Maven installation, please refer maven.apache.org. For Gradle installation, please refer gradle.org .

Support

Getting StartedDownloadsMotivationJavadoc EasyMock API extension (PowerMock class) Mockito API extension (PowerMockito class) Mockito2 API extension (PowerMockito class) PowerMock Reflect (Whitebox class)Common PowerMock Configuration Bypass Encapsulation Suppress Unwanted Behavior Test Listeners Mock Policies Mock system classesEasyMockMockitoTestNGDelegate to another JUnit RunnerBootstrap using a JUnit RuleBootstrap using a Java AgentOSGiRelease NotesFAQ

DOWNLOAD this Library from

Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

Explore Related Topics

Share this Page

share link
Reuse Pre-built Kits with powermock
Consider Popular Mock Libraries
Compare Mock Libraries with Highest Support
Find, review, and download reusable Libraries, Code Snippets, Cloud APIs from
over 430 million Knowledge Items
Find more libraries
Reuse Solution Kits and Libraries Curated by Popular Use Cases

Save this library and start creating your kit

  • © 2022 Open Weaver Inc.