Tabnine Logo
PowerMockito.when
Code IndexAdd Tabnine to your IDE (free)

How to use
when
method
in
org.powermock.api.mockito.PowerMockito

Best Java code snippets using org.powermock.api.mockito.PowerMockito.when (Showing top 20 results out of 792)

Refine searchRefine arrow

  • OngoingStubbing.thenReturn
  • Test.<init>
  • PowerMockito.mock
  • PowerMockito.mockStatic
origin: checkstyle/checkstyle

@Test
@SuppressWarnings("unchecked")
public void testListFilesNotFile() throws Exception {
  final Class<?> optionsClass = Class.forName(Main.class.getName());
  final Method method = optionsClass.getDeclaredMethod("listFiles", File.class, List.class);
  method.setAccessible(true);
  final File fileMock = mock(File.class);
  when(fileMock.canRead()).thenReturn(true);
  when(fileMock.isDirectory()).thenReturn(false);
  when(fileMock.isFile()).thenReturn(false);
  final List<File> result = (List<File>) method.invoke(null, fileMock, null);
  assertEquals("Invalid result size", 0, result.size());
}
origin: apache/flink

@Override
protected AbstractPartitionDiscoverer createPartitionDiscoverer(
    KafkaTopicsDescriptor topicsDescriptor,
    int indexOfThisSubtask,
    int numParallelSubtasks) {
  AbstractPartitionDiscoverer mockPartitionDiscoverer = mock(AbstractPartitionDiscoverer.class);
  try {
    when(mockPartitionDiscoverer.discoverPartitions()).thenReturn(partitions);
  } catch (Exception e) {
    // ignore
  }
  when(mockPartitionDiscoverer.setAndCheckDiscoveredPartition(any(KafkaTopicPartition.class))).thenReturn(true);
  return mockPartitionDiscoverer;
}
origin: Alluxio/alluxio

private void setupShellMocks(String username, List<String> groups) throws IOException {
 PowerMockito.mockStatic(CommonUtils.class);
 PowerMockito.when(CommonUtils.getUnixGroups(eq(username))).thenReturn(groups);
}
origin: spring-projects/spring-security

@Test
public void loadConfigWhenDefaultConfigurerAsSpringFactoryhenDefaultConfigurerApplied() {
  spy(SpringFactoriesLoader.class);
  DefaultConfigurer configurer = new DefaultConfigurer();
  when(SpringFactoriesLoader
      .loadFactories(AbstractHttpConfigurer.class, getClass().getClassLoader()))
    .thenReturn(Arrays.<AbstractHttpConfigurer>asList(configurer));
  loadConfig(Config.class);
  assertThat(configurer.init).isTrue();
  assertThat(configurer.configure).isTrue();
}
origin: pentaho/pentaho-kettle

@Test
public void testGetAttributesXml_DefaultTag_EmptyMap() {
 PowerMockito.when( AttributesUtil.getAttributesXml( any( Map.class ) ) ).thenCallRealMethod();
 PowerMockito.when( AttributesUtil.getAttributesXml( any( Map.class ), anyString() ) ).thenCallRealMethod();
 Map<String, Map<String, String>> attributesMap = new HashMap<>();
 String attributesXml = AttributesUtil.getAttributesXml( attributesMap );
 assertNotNull( attributesXml );
 // Check that it's not an empty XML fragment
 assertTrue( attributesXml.contains( AttributesUtil.XML_TAG ) );
}
origin: checkstyle/checkstyle

@Test
public void testExceptionNoSuchAlgorithmException() throws Exception {
  final Configuration config = new DefaultConfiguration("myName");
  final String filePath = temporaryFolder.newFile().getPath();
  final PropertyCacheFile cache = new PropertyCacheFile(config, filePath);
  cache.put("myFile", 1);
  mockStatic(MessageDigest.class);
  when(MessageDigest.getInstance("SHA-1"))
      .thenThrow(NoSuchAlgorithmException.class);
  final Class<?>[] param = new Class<?>[1];
  param[0] = Serializable.class;
  final Method method =
    PropertyCacheFile.class.getDeclaredMethod("getHashCodeBasedOnObjectContent", param);
  method.setAccessible(true);
  try {
    method.invoke(cache, config);
    fail("InvocationTargetException is expected");
  }
  catch (InvocationTargetException ex) {
    assertTrue("Invalid exception cause",
        ex.getCause().getCause() instanceof NoSuchAlgorithmException);
    assertEquals("Invalid exception message",
        "Unable to calculate hashcode.", ex.getCause().getMessage());
  }
}
origin: checkstyle/checkstyle

@Test
public void testPackagesWithIoExceptionGetResources() throws Exception {
  final ClassLoader classLoader = mock(ClassLoader.class);
  when(classLoader.getResources("checkstyle_packages.xml")).thenThrow(IOException.class);
  try {
    PackageNamesLoader.getPackageNames(classLoader);
    fail("CheckstyleException is expected");
  }
  catch (CheckstyleException ex) {
    assertTrue("Invalid exception cause class", ex.getCause() instanceof IOException);
    assertEquals("Invalid exception message",
        "unable to get package file resources", ex.getMessage());
  }
}
origin: ankidroid/Anki-Android

public static RectangleWrap createRectangleMock(int width, int height) {
  RectangleWrap r = mock(RectangleWrap.class);
  r.width = width;
  r.height = height;
  when(r.width()).thenReturn(width);
  when(r.height()).thenReturn(height);
  return r;
}
origin: konmik/nucleus

private void setUpPresenter() throws Exception {
  mockPresenter = mock(TestPresenter.class);
  mockDelegate = mock(PresenterLifecycleDelegate.class);
  PowerMockito.whenNew(PresenterLifecycleDelegate.class).withAnyArguments().thenReturn(mockDelegate);
  when(mockDelegate.getPresenter()).thenReturn(mockPresenter);
  mockFactory = mock(ReflectionPresenterFactory.class);
  when(mockFactory.createPresenter()).thenReturn(mockPresenter);
  PowerMockito.mockStatic(ReflectionPresenterFactory.class);
  when(ReflectionPresenterFactory.fromViewClass(any(Class.class))).thenReturn(mockFactory);
}
origin: checkstyle/checkstyle

@Test
@SuppressWarnings("unchecked")
public void testListFilesDirectoryWithNull() throws Exception {
  final Class<?> optionsClass = Class.forName(Main.class.getName());
  final Method method = optionsClass.getDeclaredMethod("listFiles", File.class, List.class);
  method.setAccessible(true);
  final File fileMock = mock(File.class);
  when(fileMock.canRead()).thenReturn(true);
  when(fileMock.isDirectory()).thenReturn(true);
  when(fileMock.listFiles()).thenReturn(null);
  final List<File> result = (List<File>) method.invoke(null, fileMock,
      new ArrayList<Pattern>());
  assertEquals("Invalid result size", 0, result.size());
}
origin: spring-projects/spring-security

@Test
public void createExpressionMessageMetadataSourceMatchFirst() {
  when(matcher1.matches(message)).thenReturn(true);
  Collection<ConfigAttribute> attrs = source.getAttributes(message);
  assertThat(attrs).hasSize(1);
  ConfigAttribute attr = attrs.iterator().next();
  assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
  assertThat(
      ((MessageExpressionConfigAttribute) attr).getAuthorizeExpression()
          .getValue(rootObject)).isEqualTo(true);
}
origin: pentaho/pentaho-kettle

@Test
public void testGetAttributesXml_DefaultTag_NullParameter() {
 PowerMockito.when( AttributesUtil.getAttributesXml( any( Map.class ) ) ).thenCallRealMethod();
 PowerMockito.when( AttributesUtil.getAttributesXml( any( Map.class ), anyString() ) ).thenCallRealMethod();
 String attributesXml = AttributesUtil.getAttributesXml( null );
 assertNotNull( attributesXml );
 // Check that it's not an empty XML fragment
 assertTrue( attributesXml.contains( AttributesUtil.XML_TAG ) );
}
origin: facebook/facebook-android-sdk

private void mockCustomTabsAllowed(final boolean allowed) {
  final FetchedAppSettings settings = mock(FetchedAppSettings.class);
  when(settings.getCustomTabsEnabled()).thenReturn(allowed);
  mockStatic(FetchedAppSettingsManager.class);
  when(FetchedAppSettingsManager.getAppSettingsWithoutQuery(anyString())).thenReturn(settings);
}
origin: ankidroid/Anki-Android

private ColorWrap createColorMock(int i) {
  ColorWrap c = mock(ColorWrap.class);
  when(c.getColorValue()).thenReturn(i);
  return c;
}
origin: konmik/nucleus

private void setUpPresenter() throws Exception {
  mockPresenter = mock(TestPresenter.class);
  mockDelegate = mock(PresenterLifecycleDelegate.class);
  PowerMockito.whenNew(PresenterLifecycleDelegate.class).withAnyArguments().thenReturn(mockDelegate);
  when(mockDelegate.getPresenter()).thenReturn(mockPresenter);
  mockFactory = mock(ReflectionPresenterFactory.class);
  when(mockFactory.createPresenter()).thenReturn(mockPresenter);
  PowerMockito.mockStatic(ReflectionPresenterFactory.class);
  when(ReflectionPresenterFactory.fromViewClass(any(Class.class))).thenReturn(mockFactory);
}
origin: facebook/facebook-android-sdk

@Before
public void setup() {
 mockStatic(Utility.class);
 mMockActivity = mock(Activity.class);
 mMockPackageManager = mock(PackageManager.class);
 when(mMockActivity.getPackageManager()).thenReturn(mMockPackageManager);
}
origin: spring-projects/spring-security

  @Test
  public void createExpressionMessageMetadataSourceMatchSecond() {
    when(matcher2.matches(message)).thenReturn(true);

    Collection<ConfigAttribute> attrs = source.getAttributes(message);

    assertThat(attrs).hasSize(1);
    ConfigAttribute attr = attrs.iterator().next();
    assertThat(attr).isInstanceOf(MessageExpressionConfigAttribute.class);
    assertThat(
        ((MessageExpressionConfigAttribute) attr).getAuthorizeExpression()
            .getValue(rootObject)).isEqualTo(false);
  }
}
origin: pentaho/pentaho-kettle

@Test
public void testGetAttributesXml_CustomTag_EmptyMap() {
 PowerMockito.when( AttributesUtil.getAttributesXml( any( Map.class ), anyString() ) ).thenCallRealMethod();
 Map<String, Map<String, String>> attributesMap = new HashMap<>();
 String attributesXml = AttributesUtil.getAttributesXml( attributesMap, CUSTOM_TAG );
 assertNotNull( attributesXml );
 // Check that it's not an empty XML fragment
 assertTrue( attributesXml.contains( CUSTOM_TAG ) );
}
origin: facebook/facebook-android-sdk

private void mockTryAuthorize() {
  mockStatic(FacebookSdk.class);
  when(FacebookSdk.isInitialized()).thenReturn(true);
  mockStatic(AccessToken.class);
  when(AccessToken.getCurrentAccessToken()).thenReturn(null);
  Fragment fragment = mock(LoginFragment.class);
  when(mockLoginClient.getFragment()).thenReturn(fragment);
}
origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 mContext = PowerMockito.mock(FileSystemContext.class);
 mAddress = mock(WorkerNetAddress.class);
 mClient = mock(BlockWorkerClient.class);
 mRequestObserver = mock(ClientCallStreamObserver.class);
 PowerMockito.when(mContext.acquireBlockWorkerClient(mAddress)).thenReturn(mClient);
 PowerMockito.when(mContext.getClientContext())
   .thenReturn(ClientContext.create(mConf));
 PowerMockito.when(mContext.getConf()).thenReturn(mConf);
 PowerMockito.doNothing().when(mContext).releaseBlockWorkerClient(mAddress, mClient);
 PowerMockito.when(mClient.writeBlock(any(StreamObserver.class))).thenReturn(mRequestObserver);
 PowerMockito.when(mRequestObserver.isReady()).thenReturn(true);
}
org.powermock.api.mockitoPowerMockitowhen

Javadoc

Expect a static private or inner class method call.

Popular methods of PowerMockito

  • mockStatic
    Enable static mocking for all methods of a class.
  • mock
    Creates mock with a specified strategy for its answers to interactions. It's quite advanced feature
  • verifyStatic
    Verifies certain behavior happened at least once / exact number of times / never. E.g: verifyStatic
  • spy
    Spy on objects that are final or otherwise not "spyable" from normal Mockito.
  • whenNew
    Allows specifying expectations on new invocations. For example you might want to throw an exception
  • doReturn
    Same as #doReturn(Object) but sets consecutive values to be returned. Remember to usedoReturn() in t
  • doNothing
    Use doNothing() for setting void methods to do nothing. Beware that void methods on mocks do nothing
  • doThrow
    Use doThrow() when you want to stub the void method with an exception. Stubbing voids requires diffe
  • doAnswer
    Use doAnswer() when you want to stub a void method with generic Answer. Stubbing voids requires diff
  • verifyZeroInteractions
    Verifies that no interactions happened on given mocks (can be both instance and class mocks). Delega
  • method
  • verifyNew
    Verifies certain behavior happened at least once / exact number of times / never. E.g: verifyNew(Cl
  • method,
  • verifyNew,
  • verifyPrivate,
  • stub,
  • doCallRealMethod,
  • field,
  • verifyNoMoreInteractions,
  • constructor,
  • replace

Popular in Java

  • Updating database using SQL prepared statement
  • getSupportFragmentManager (FragmentActivity)
  • onRequestPermissionsResult (Fragment)
  • compareTo (BigDecimal)
  • GridLayout (java.awt)
    The GridLayout class is a layout manager that lays out a container's components in a rectangular gri
  • DecimalFormat (java.text)
    A concrete subclass of NumberFormat that formats decimal numbers. It has a variety of features desig
  • Queue (java.util)
    A collection designed for holding elements prior to processing. Besides basic java.util.Collection o
  • StringTokenizer (java.util)
    Breaks a string into tokens; new code should probably use String#split.> // Legacy code: StringTo
  • BlockingQueue (java.util.concurrent)
    A java.util.Queue that additionally supports operations that wait for the queue to become non-empty
  • Modifier (javassist)
    The Modifier class provides static methods and constants to decode class and member access modifiers
  • Top Vim plugins
Tabnine Logo
  • Products

    Search for Java codeSearch for JavaScript code
  • IDE Plugins

    IntelliJ IDEAWebStormVisual StudioAndroid StudioEclipseVisual Studio CodePyCharmSublime TextPhpStormVimGoLandRubyMineEmacsJupyter NotebookJupyter LabRiderDataGripAppCode
  • Company

    About UsContact UsCareers
  • Resources

    FAQBlogTabnine AcademyTerms of usePrivacy policyJava Code IndexJavascript Code Index
Get Tabnine for your IDE now