本文整理汇总了Java中org.mockito.internal.util.reflection.Whitebox类的典型用法代码示例。如果您正苦于以下问题:Java Whitebox类的具体用法?Java Whitebox怎么用?Java Whitebox使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Whitebox类属于org.mockito.internal.util.reflection包,在下文中一共展示了Whitebox类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。
示例1: testFileStatusPipeFile
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void testFileStatusPipeFile() throws Exception {
RawLocalFileSystem origFs = new RawLocalFileSystem();
RawLocalFileSystem fs = spy(origFs);
Configuration conf = mock(Configuration.class);
fs.setConf(conf);
Whitebox.setInternalState(fs, "useDeprecatedFileStatus", false);
Path path = new Path("/foo");
File pipe = mock(File.class);
when(pipe.isFile()).thenReturn(false);
when(pipe.isDirectory()).thenReturn(false);
when(pipe.exists()).thenReturn(true);
FileStatus stat = mock(FileStatus.class);
doReturn(pipe).when(fs).pathToFile(path);
doReturn(stat).when(fs).getFileStatus(path);
FileStatus[] stats = fs.listStatus(path);
assertTrue(stats != null && stats.length == 1 && stats[0] == stat);
}
示例2: checkBindAddress
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
private HttpServer2 checkBindAddress(String host, int port, boolean findPort)
throws Exception {
HttpServer2 server = createServer(host, port);
try {
// not bound, ephemeral should return requested port (0 for ephemeral)
List<?> listeners = (List<?>) Whitebox.getInternalState(server,
"listeners");
Connector listener = (Connector) listeners.get(0);
assertEquals(port, listener.getPort());
// verify hostname is what was given
server.openListeners();
assertEquals(host, server.getConnectorAddress(0).getHostName());
int boundPort = server.getConnectorAddress(0).getPort();
if (port == 0) {
assertTrue(boundPort != 0); // ephemeral should now return bound port
} else if (findPort) {
assertTrue(boundPort > port);
}
} catch (Exception e) {
server.stop();
throw e;
}
return server;
}
示例3: isBtcTxHashAlreadyProcessed_normalFlow
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void isBtcTxHashAlreadyProcessed_normalFlow() throws IOException {
Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR);
bridge.init(null, null, null, null, null, null);
BridgeSupport bridgeSupportMock = mock(BridgeSupport.class);
Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock);
Set<Sha256Hash> hashes = new HashSet<>();
when(bridgeSupportMock.isBtcTxHashAlreadyProcessed(any(Sha256Hash.class))).then((InvocationOnMock invocation) -> hashes.contains(invocation.getArgumentAt(0, Sha256Hash.class)));
hashes.add(Sha256Hash.of("hash_1".getBytes()));
hashes.add(Sha256Hash.of("hash_2".getBytes()));
hashes.add(Sha256Hash.of("hash_3".getBytes()));
hashes.add(Sha256Hash.of("hash_4".getBytes()));
for (Sha256Hash hash : hashes) {
Assert.assertTrue(bridge.isBtcTxHashAlreadyProcessed(new Object[]{hash.toString()}));
verify(bridgeSupportMock).isBtcTxHashAlreadyProcessed(hash);
}
Assert.assertFalse(bridge.isBtcTxHashAlreadyProcessed(new Object[]{Sha256Hash.of("anything".getBytes()).toString()}));
Assert.assertFalse(bridge.isBtcTxHashAlreadyProcessed(new Object[]{Sha256Hash.of("yetanotheranything".getBytes()).toString()}));
}
示例4: isBtcTxHashAlreadyProcessed_exception
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void isBtcTxHashAlreadyProcessed_exception() throws IOException {
Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR);
bridge.init(null, null, null, null, null, null);
BridgeSupport bridgeSupportMock = mock(BridgeSupport.class);
Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock);
boolean thrown = false;
try {
bridge.isBtcTxHashAlreadyProcessed(new Object[]{"notahash"});
} catch (RuntimeException e) {
thrown = true;
}
Assert.assertTrue(thrown);
verify(bridgeSupportMock, never()).isBtcTxHashAlreadyProcessed(any());
}
示例5: setUp
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Before
public void setUp() {
// not sure why, but adapter does not get injected properly, hence a workaround here:
Whitebox.setInternalState(governor, "bluetoothObject", adapter);
when(adapter.isPowered()).thenReturn(POWERED);
when(adapter.isDiscovering()).thenReturn(DISCOVERING);
when(adapter.getAlias()).thenReturn(ALIAS);
when(adapter.getName()).thenReturn(NAME);
doNothing().when(adapter).enablePoweredNotifications(poweredCaptor.capture());
doNothing().when(adapter).enableDiscoveringNotifications(discoveringCaptor.capture());
governor.addAdapterListener(listener);
when(adapter.getURL()).thenReturn(URL);
PowerMockito.mockStatic(BluetoothObjectFactoryProvider.class);
when(BluetoothObjectFactoryProvider.getFactory(any())).thenReturn(bluetoothObjectFactory);
when(bluetoothObjectFactory.getAdapter(URL)).thenReturn(adapter);
when(adapter.getDevices()).thenReturn(DEVICES);
}
示例6: getBtcTxHashProcessedHeight_exception
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void getBtcTxHashProcessedHeight_exception() throws IOException {
Bridge bridge = new Bridge(ConfigHelper.CONFIG, PrecompiledContracts.BRIDGE_ADDR);
bridge.init(null, null, null, null, null, null);
BridgeSupport bridgeSupportMock = mock(BridgeSupport.class);
Whitebox.setInternalState(bridge, "bridgeSupport", bridgeSupportMock);
boolean thrown = false;
try {
bridge.getBtcTxHashProcessedHeight(new Object[]{"notahash"});
} catch (RuntimeException e) {
thrown = true;
}
Assert.assertTrue(thrown);
verify(bridgeSupportMock, never()).getBtcTxHashProcessedHeight(any());
}
示例7: testRegionOpenFailsDueToIOException
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
/**
* If region open fails with IOException in openRegion() while doing tableDescriptors.get()
* the region should not add into regionsInTransitionInRS map
* @throws Exception
*/
@Test
public void testRegionOpenFailsDueToIOException() throws Exception {
HRegionInfo REGIONINFO = new HRegionInfo(TableName.valueOf("t"),
HConstants.EMPTY_START_ROW, HConstants.EMPTY_START_ROW);
HRegionServer regionServer = TEST_UTIL.getHBaseCluster().getRegionServer(0);
TableDescriptors htd = Mockito.mock(TableDescriptors.class);
Object orizinalState = Whitebox.getInternalState(regionServer,"tableDescriptors");
Whitebox.setInternalState(regionServer, "tableDescriptors", htd);
Mockito.doThrow(new IOException()).when(htd).get((TableName) Mockito.any());
try {
ProtobufUtil.openRegion(null, regionServer.getRSRpcServices(),
regionServer.getServerName(), REGIONINFO);
fail("It should throw IOException ");
} catch (IOException e) {
}
Whitebox.setInternalState(regionServer, "tableDescriptors", orizinalState);
assertFalse("Region should not be in RIT",
regionServer.getRegionsInTransitionInRS().containsKey(REGIONINFO.getEncodedNameAsBytes()));
}
示例8: testMetaFile
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void testMetaFile() throws Exception {
RaftStorage storage = new RaftStorage(storageDir, StartupOption.FORMAT);
File m = storage.getStorageDir().getMetaFile();
Assert.assertTrue(m.exists());
MetaFile metaFile = new MetaFile(m);
Assert.assertEquals(MetaFile.DEFAULT_TERM, metaFile.getTerm());
Assert.assertEquals(MetaFile.EMPTY_VOTEFOR, metaFile.getVotedFor());
metaFile.set(123, "peer1");
metaFile.readFile();
Assert.assertEquals(123, metaFile.getTerm());
Assert.assertEquals("peer1", metaFile.getVotedFor());
MetaFile metaFile2 = new MetaFile(m);
Assert.assertFalse((Boolean) Whitebox.getInternalState(metaFile2, "loaded"));
Assert.assertEquals(123, metaFile.getTerm());
Assert.assertEquals("peer1", metaFile.getVotedFor());
storage.close();
}
示例9: setupMethod
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@BeforeMethod
public void setupMethod() throws Exception {
this.evaluationService = new PolicyEvaluationServiceImpl();
MockitoAnnotations.initMocks(this);
Whitebox.setInternalState(this.policyMatcher, "attributeReaderFactory", this.attributeReaderFactory);
Whitebox.setInternalState(this.evaluationService, "policyMatcher", this.policyMatcher);
Whitebox.setInternalState(this.evaluationService, "policySetValidator", this.policySetValidator);
when(this.zoneResolver.getZoneEntityOrFail()).thenReturn(new ZoneEntity(0L, "testzone"));
when(this.cache.get(any(PolicyEvaluationRequestCacheKey.class))).thenReturn(null);
when(this.attributeReaderFactory.getResourceAttributeReader()).thenReturn(this.externalResourceAttributeReader);
when(this.attributeReaderFactory.getSubjectAttributeReader()).thenReturn(this.externalSubjectAttributeReader);
PolicySet policySet = new ObjectMapper().readValue(
new File("src/test/resources/policy-set-with-one-policy-one-condition-using-res-attributes.json"),
PolicySet.class);
when(this.policyService.getAllPolicySets()).thenReturn(Collections.singletonList(policySet));
}
示例10: testCloseTwice
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
/**
* The close() method of DFSOutputStream should never throw the same exception
* twice. See HDFS-5335 for details.
*/
@Test
public void testCloseTwice() throws IOException {
DistributedFileSystem fs = cluster.getFileSystem();
FSDataOutputStream os = fs.create(new Path("/test"));
DFSOutputStream dos = (DFSOutputStream) Whitebox.getInternalState(os,
"wrappedStream");
@SuppressWarnings("unchecked")
AtomicReference<IOException> ex = (AtomicReference<IOException>) Whitebox
.getInternalState(dos, "lastException");
Assert.assertEquals(null, ex.get());
dos.close();
IOException dummy = new IOException("dummy");
ex.set(dummy);
try {
dos.close();
} catch (IOException e) {
Assert.assertEquals(e, dummy);
}
Assert.assertEquals(null, ex.get());
dos.close();
}
示例11: testGetRemoteToken
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void testGetRemoteToken() throws IOException, URISyntaxException {
Configuration conf = new Configuration();
DummyFs fs = spy(new DummyFs());
Token<TokenIdentifier> token = new Token<TokenIdentifier>(new byte[0],
new byte[0], DummyFs.TOKEN_KIND, new Text("127.0.0.1:1234"));
doReturn(token).when(fs).getDelegationToken(anyString());
doReturn(token).when(fs).getRenewToken();
fs.initialize(new URI("dummyfs://127.0.0.1:1234"), conf);
fs.tokenAspect.ensureTokenInitialized();
// Select a token, store and renew it
verify(fs).setDelegationToken(token);
assertNotNull(Whitebox.getInternalState(fs.tokenAspect, "dtRenewer"));
assertNotNull(Whitebox.getInternalState(fs.tokenAspect, "action"));
}
示例12: run
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Override
public void run() {
try {
Thread.sleep(1000);
LOG.info("Deleting" + path);
final FSDirectory fsdir = cluster.getNamesystem().dir;
INode fileINode = fsdir.getINode4Write(path.toString());
INodeMap inodeMap = (INodeMap) Whitebox.getInternalState(fsdir,
"inodeMap");
fs.delete(path, false);
// after deletion, add the inode back to the inodeMap
inodeMap.put(fileINode);
LOG.info("Deleted" + path);
} catch (Exception e) {
LOG.info(e);
}
}
示例13: testInternalNameService
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void testInternalNameService() throws Exception {
Configuration conf = new Configuration();
conf.set(DFSConfigKeys.DFS_NAMESERVICES, "ns1,ns2,ns3");
addNN(conf, "ns1", "mock1:8020");
addNN(conf, "ns2", "mock1:8020");
addNN(conf, "ns3", "mock1:8020");
conf.set(DFSConfigKeys.DFS_INTERNAL_NAMESERVICES_KEY, "ns1");
bpm.refreshNamenodes(conf);
assertEquals("create #1\n", log.toString());
@SuppressWarnings("unchecked")
Map<String, BPOfferService> map = (Map<String, BPOfferService>) Whitebox
.getInternalState(bpm, "bpByNameserviceId");
Assert.assertFalse(map.containsKey("ns2"));
Assert.assertFalse(map.containsKey("ns3"));
Assert.assertTrue(map.containsKey("ns1"));
log.setLength(0);
}
示例14: testUpdateNotReadyToReady
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test
public void testUpdateNotReadyToReady() throws Exception {
// conditions
Whitebox.setInternalState(governor, "bluetoothObject", null);
governor.addGovernorListener(governorListener);
governor.update();
InOrder inOrder = inOrder(governor, governorListener, bluetoothManager);
inOrder.verify(bluetoothManager).getBluetoothObject(URL);
inOrder.verify(governor).init(bluetoothObject);
inOrder.verify(governorListener).ready(true);
inOrder.verify(governor).update(bluetoothObject);
inOrder.verify(governorListener, never()).lastUpdatedChanged(any());
governor.updateLastChanged();
governor.update();
inOrder.verify(governorListener).lastUpdatedChanged(any());
inOrder.verifyNoMoreInteractions();
}
示例15: testPutMetrics
import org.mockito.internal.util.reflection.Whitebox; //导入依赖的package包/类
@Test(timeout=3000)
public void testPutMetrics() throws IOException, InterruptedException {
final StatsDSink sink = new StatsDSink();
List<MetricsTag> tags = new ArrayList<MetricsTag>();
tags.add(new MetricsTag(MsInfo.Hostname, "host"));
tags.add(new MetricsTag(MsInfo.Context, "jvm"));
tags.add(new MetricsTag(MsInfo.ProcessName, "process"));
Set<AbstractMetric> metrics = new HashSet<AbstractMetric>();
metrics.add(makeMetric("foo1", 1.25, MetricType.COUNTER));
metrics.add(makeMetric("foo2", 2.25, MetricType.GAUGE));
final MetricsRecord record =
new MetricsRecordImpl(MsInfo.Context, (long) 10000, tags, metrics);
try (DatagramSocket sock = new DatagramSocket()) {
sock.setReceiveBufferSize(8192);
final StatsDSink.StatsD mockStatsD =
new StatsD(sock.getLocalAddress().getHostName(),
sock.getLocalPort());
Whitebox.setInternalState(sink, "statsd", mockStatsD);
final DatagramPacket p = new DatagramPacket(new byte[8192], 8192);
sink.putMetrics(record);
sock.receive(p);
String result =new String(p.getData(), 0, p.getLength(),
Charset.forName("UTF-8"));
assertTrue(
"Received data did not match data sent",
result.equals("host.process.jvm.Context.foo1:1.25|c") ||
result.equals("host.process.jvm.Context.foo2:2.25|g"));
} finally {
sink.close();
}
}