org.powermock.api.mockito.PowerMockito.mockStatic()方法的使用及代码示例

x33g5p2x  于2022-01-26 转载在 其他  
字(11.3k)|赞(0)|评价(0)|浏览(223)

本文整理了Java中org.powermock.api.mockito.PowerMockito.mockStatic()方法的一些代码示例,展示了PowerMockito.mockStatic()的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。PowerMockito.mockStatic()方法的具体详情如下:
包路径:org.powermock.api.mockito.PowerMockito
类名称:PowerMockito
方法名:mockStatic

PowerMockito.mockStatic介绍

[英]Creates a class mock with some non-standard settings.

The number of configuration points for a mock grows so we need a fluent way to introduce new configuration without adding more and more overloaded PowerMockito.mockStatic() methods. Hence MockSettings.

mockStatic(Listener.class, withSettings() 
.name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); 
);

Use it carefully and occasionally. What might be reason your test needs non-standard mocks? Is the code under test so complicated that it requires non-standard mocks? Wouldn't you prefer to refactor the code under test so it is testable in a simple way?

See also Mockito#withSettings()
[中]使用一些非标准设置创建类mock。
模拟的配置点数量在增加,因此我们需要一种流畅的方式来引入新的配置,而不需要添加越来越多的重载PowerMockito。mockStatic()方法。因此,模拟设置。

mockStatic(Listener.class, withSettings() 
.name("firstListner").defaultBehavior(RETURNS_SMART_NULLS)); 
);

小心使用,偶尔使用。您的测试需要非标准模拟的原因可能是什么?被测代码是否如此复杂,以至于需要非标准模拟?难道你不喜欢重构被测试的代码,让它以一种简单的方式进行测试吗?
另见Mockito#with settings()

代码示例

代码示例来源:origin: Alluxio/alluxio

private void mockUserGroupInformation(String username) throws IOException {
 // need to mock out since FileSystem.create calls UGI, which occasionally has issues on some
 // systems
 PowerMockito.mockStatic(UserGroupInformation.class);
 final UserGroupInformation ugi = mock(UserGroupInformation.class);
 when(UserGroupInformation.getCurrentUser()).thenReturn(ugi);
 when(ugi.getUserName()).thenReturn(username);
 when(ugi.getShortUserName()).thenReturn(username.split("@")[0]);
}

代码示例来源: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: 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: Alluxio/alluxio

@Test
public void run() throws Exception {
 JobCoordinator coordinator = PowerMockito.mock(JobCoordinator.class);
 PowerMockito.mockStatic(JobCoordinator.class);
 Mockito.when(
   JobCoordinator.create(Mockito.any(CommandManager.class), Mockito.any(UfsManager.class),
     Mockito.anyList(), Mockito.anyLong(), Mockito.any(JobConfig.class), Mockito.any(null)))
   .thenReturn(coordinator);
 TestJobConfig jobConfig = new TestJobConfig("/test");
 for (long i = 0; i < TEST_JOB_MASTER_JOB_CAPACITY; i++) {
  mJobMaster.run(jobConfig);
 }
 Assert.assertEquals(TEST_JOB_MASTER_JOB_CAPACITY, mJobMaster.list().size());
}

代码示例来源:origin: julian-klode/dns66

@Before
public void setUp() {
  mockStatic(Log.class);
  service = mock(AdVpnService.class);
  thread = new AdVpnThread(service, null);
  builder = mock(VpnService.Builder.class);
  when(builder.addDnsServer(anyString())).thenAnswer(new Answer<VpnService.Builder>() {
    @Override
    public VpnService.Builder answer(InvocationOnMock invocation) throws Throwable {
  when(builder.addDnsServer(any(InetAddress.class))).thenAnswer(new Answer<VpnService.Builder>() {
    @Override
    public VpnService.Builder answer(InvocationOnMock invocation) throws Throwable {

代码示例来源: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: facebook/litho

@Before
public void setup() throws Exception {
 mainService = mock(ExecutorCompletionService.class);
 bgService = mock(ExecutorCompletionService.class);
 mockStatic(ThreadUtils.class);
 mContext = new ComponentContext(new ContextWrapper(RuntimeEnvironment.application));

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() {
 mMockJobMasterContext = Mockito.mock(JobMasterContext.class);
 mMockFileSystem = Mockito.mock(FileSystem.class);
 mMockFileSystemContext = PowerMockito.mock(FileSystemContext.class);
 mMockBlockStore = PowerMockito.mock(AlluxioBlockStore.class);
 PowerMockito.mockStatic(AlluxioBlockStore.class);
 PowerMockito.when(AlluxioBlockStore.create(mMockFileSystemContext)).thenReturn(mMockBlockStore);
}

代码示例来源:origin: facebook/facebook-android-sdk

private void mockCustomTabRedirectActivity(final boolean hasActivity) {
  mockStatic(Validate.class);
  when(Validate.hasCustomTabRedirectActivity(any(Context.class))).thenReturn(hasActivity);
}

代码示例来源:origin: apache/kylin

protected void setupProperties() {
  connection = mock(Connection.class);
  dbmd = mock(DatabaseMetaData.class);
  PowerMockito.mockStatic(SqlUtil.class);
  when(SqlUtil.getConnection(dbConnConf)).thenReturn(connection);
}

代码示例来源:origin: facebook/litho

@Before
public void setUp() {
 mDiffNode = mock(DiffNode.class);
 mNode = mock(InternalNode.class);
 final YogaNode cssNode = new YogaNode();
 cssNode.setData(mNode);
 mNode.mYogaNode = cssNode;
 mockStatic(ComponentsPools.class);
 when(mNode.getLastWidthSpec()).thenReturn(-1);
 when(mNode.getDiffNode()).thenReturn(mDiffNode);
 when(mDiffNode.getLastMeasuredWidth()).thenReturn(-1f);
 when(mDiffNode.getLastMeasuredHeight()).thenReturn(-1f);
 when(ComponentsPools.acquireInternalNode(any(ComponentContext.class))).thenReturn(mNode);
 when(ComponentsPools.acquireComponentTreeBuilder(
     any(ComponentContext.class), any(Component.class)))
   .thenCallRealMethod();
 mockStatic(LayoutState.class);
 StateHandler stateHandler = mock(StateHandler.class);
 mContext = spy(new ComponentContext(RuntimeEnvironment.application, stateHandler));
 mNestedTreeWidthSpec = SizeSpec.makeSizeSpec(400, SizeSpec.EXACTLY);
 mNestedTreeHeightSpec = SizeSpec.makeSizeSpec(200, SizeSpec.EXACTLY);
}

代码示例来源:origin: julian-klode/dns66

@Test
@PrepareForTest(Log.class)
public void testCloseOrWarn_closeable() throws Exception {
  Closeable closeable = mock(Closeable.class);
  mockStatic(Log.class);
  when(Log.e(anyString(), anyString(), any(Throwable.class))).then(new CountingAnswer(null));
  // Closing null should work just fine
  testResult = 0;
  assertNull(FileHelper.closeOrWarn((Closeable) null, "tag", "msg"));
  assertEquals(0, testResult);
  // Successfully closing the file should not log.
  testResult = 0;
  assertNull(FileHelper.closeOrWarn(closeable, "tag", "msg"));
  assertEquals(0, testResult);
  // If closing fails, it should log.
  when(closeable).thenThrow(new IOException("Foobar"));
  testResult = 0;
  assertNull(FileHelper.closeOrWarn(closeable, "tag", "msg"));
  assertEquals(1, testResult);
}

代码示例来源:origin: checkstyle/checkstyle

mockStatic(CommonUtil.class);
final CheckstyleException mockException =
  new CheckstyleException("Cannot get URL for cache file " + cacheFile.getAbsolutePath());
when(CommonUtil.getUriByFilename(any(String.class)))
  .thenThrow(mockException);

代码示例来源:origin: Alluxio/alluxio

@Before
public void before() throws Exception {
 mMockFileSystemContext = PowerMockito.mock(FileSystemContext.class);
 mMockBlockStore = PowerMockito.mock(AlluxioBlockStore.class);
 mMockFileSystem = Mockito.mock(FileSystem.class);
 mMockUfsManager = Mockito.mock(UfsManager.class);
 PowerMockito.mockStatic(AlluxioBlockStore.class);
 PowerMockito.when(AlluxioBlockStore.create(mMockFileSystemContext)).thenReturn(mMockBlockStore);
 when(mMockBlockStore.getAllWorkers()).thenReturn(BLOCK_WORKERS);
 createDirectory("/");
}

代码示例来源:origin: apache/geode

private ReferenceCountHelperImpl prepareInstance() {
 ReferenceCountHelperImpl rchi = mock(ReferenceCountHelperImpl.class);
 PowerMockito.mockStatic(ReferenceCountHelper.class, Mockito.CALLS_REAL_METHODS);
 PowerMockito.when(ReferenceCountHelper.getInstance()).thenReturn(rchi);
 return rchi;
}

代码示例来源:origin: pentaho/pentaho-kettle

@Before
public void setup() throws Exception {
 PowerMockito.mockStatic( SSHData.class );
 PowerMockito.mockStatic( KettleVFS.class );
 when( SSHData.createConnection( server, port ) ).thenReturn( connection );
 when( SSHData.OpenConnection( any(), anyInt(), any(), any(), anyBoolean(),
  any(), any(), anyInt(), anyObject(), any(), anyInt(), any(), any() ) ).thenCallRealMethod();
 when( KettleVFS.getFileObject( keyFilePath ) ).thenReturn( fileObject );
}

代码示例来源:origin: Alluxio/alluxio

@Test
public void flowControl() throws Exception {
 JobCoordinator coordinator = PowerMockito.mock(JobCoordinator.class);
 PowerMockito.mockStatic(JobCoordinator.class);
 Mockito.when(
   JobCoordinator.create(Mockito.any(CommandManager.class), Mockito.any(UfsManager.class),
     Mockito.anyList(), Mockito.anyLong(), Mockito.any(JobConfig.class), Mockito.any(null)))
   .thenReturn(coordinator);
 TestJobConfig jobConfig = new TestJobConfig("/test");
 for (long i = 0; i < TEST_JOB_MASTER_JOB_CAPACITY; i++) {
  mJobMaster.run(jobConfig);
 }
 try {
  mJobMaster.run(jobConfig);
  Assert.fail("should not be able to run more jobs than job master capacity");
 } catch (ResourceExhaustedException e) {
  Assert.assertEquals(ExceptionMessage.JOB_MASTER_FULL_CAPACITY
    .getMessage(ServerConfiguration.get(PropertyKey.JOB_MASTER_JOB_CAPACITY)),
    e.getMessage());
 }
}

代码示例来源:origin: julian-klode/dns66

@Test
@PrepareForTest({Log.class, Os.class})
public void testCloseOrWarn_fileDescriptor() throws Exception {
  FileDescriptor fd = mock(FileDescriptor.class);
  mockStatic(Log.class);
  mockStatic(Os.class);
  when(Log.e(anyString(), anyString(), any(Throwable.class))).then(new CountingAnswer(null));
  // Closing null should work just fine
  testResult = 0;
  assertNull(FileHelper.closeOrWarn((FileDescriptor) null, "tag", "msg"));
  assertEquals(0, testResult);
  // Successfully closing the file should not log.
  testResult = 0;
  assertNull(FileHelper.closeOrWarn(fd, "tag", "msg"));
  assertEquals(0, testResult);
  // If closing fails, it should log.
  testResult = 0;
  doThrow(new ErrnoException("close", 0)).when(Os.class, "close", any(FileDescriptor.class));
  assertNull(FileHelper.closeOrWarn(fd, "tag", "msg"));
  assertEquals(1, testResult);
}

代码示例来源:origin: checkstyle/checkstyle

mockStatic(CommonUtil.class);
final CheckstyleException mockException = new CheckstyleException("Exception #" + i);
when(CommonUtil.getUriByFilename(any(String.class)))
  .thenThrow(mockException);

代码示例来源: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);
}

相关文章