Java Code Examples for org.powermock.api.mockito.PowerMockito#suppress()

The following examples show how to use org.powermock.api.mockito.PowerMockito#suppress() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: CellularDeviceTest.java    From xbee-java with Mozilla Public License 2.0 6 votes vote down vote up
@Before
public void setup() throws Exception {
	// Suppress the 'readDeviceInfo' method of the parent class so that it is not
	// called from the child (CellularDevice) class.
	PowerMockito.suppress(PowerMockito.method(IPDevice.class, "readDeviceInfo"));
	
	// Spy the CellularDevice class.
	SerialPortRxTx mockPort = Mockito.mock(SerialPortRxTx.class);
	cellularDevice = PowerMockito.spy(new CellularDevice(mockPort));
	
	// Mock an IMEI address object.
	imeiAddress = PowerMockito.mock(XBeeIMEIAddress.class);
	
	// Always return a valid Cellular association indication when requested.
	PowerMockito.mockStatic(CellularAssociationIndicationStatus.class);
	PowerMockito.when(CellularAssociationIndicationStatus.get(Mockito.anyInt())).thenReturn(validCellularAIStatus);
}
 
Example 2
Source File: IOContainerTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setupClass() throws Exception {
    // this is how you mock singleton whose instance is declared
    // as private static final, as the case for Configuration.class
    PowerMockito.suppress(PowerMockito.constructor(Configuration.class));
    mockConfiguration = PowerMockito.mock(Configuration.class);
    PowerMockito.mockStatic(Configuration.class);
    when(Configuration.getInstance()).thenReturn(mockConfiguration);
}
 
Example 3
Source File: IOConfigTest.java    From blueflood with Apache License 2.0 5 votes vote down vote up
@BeforeClass
public static void setup() throws Exception {
    // this is how you mock singleton whose instance is declared
    // as private static final, as the case for Configuration.class
    PowerMockito.suppress(PowerMockito.constructor(Configuration.class));
    mockConfiguration = PowerMockito.mock(Configuration.class);
    PowerMockito.mockStatic(Configuration.class);
    when(Configuration.getInstance()).thenReturn(mockConfiguration);
}
 
Example 4
Source File: NBIoTDeviceTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
/**
 * Test method for {@link com.digi.xbee.api.NBIoTDevice#open()}.
 * 
 * <p>Verify that the {@code open()} method throws an exception when the
 * protocol is not NB-IoT.</p>
 * 
 * @throws Exception
 */
@Test
public void testNotNBIoTDevice() throws Exception {
	// Suppress the 'readDeviceInfo' method of the parent class so that it is not
	// called from the child (NBIoTDevice) class.
	PowerMockito.suppress(PowerMockito.method(CellularDevice.class, "open"));
	
	exception.expect(XBeeDeviceException.class);
	exception.expectMessage(is(equalTo("XBee device is not a Cellular NB-IoT device, it is a Unknown device.")));
	
	// Call the method that should throw the exception.
	nbiotDevice.open();
}
 
Example 5
Source File: ProtocolRemovedCommandTest.java    From ovsdb with Eclipse Public License 1.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
@Ignore("This needs to be rewritten")
public void testExecute() throws Exception {
    PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(InstanceIdentifier.class));

    ProtocolEntry protocol = mock(ProtocolEntry.class);
    when(protocol.getProtocol()).thenAnswer(
            (Answer<Class<? extends OvsdbBridgeProtocolBase>>) invocation -> OvsdbBridgeProtocolOpenflow10.class);

    BridgeOperationalState bridgeOpState = mock(BridgeOperationalState.class);
    when(bridgeOpState.getProtocolEntry(any(InstanceIdentifier.class))).thenReturn(Optional.of(protocol));

    InstanceIdentifier<ProtocolEntry> protocolIid = mock(InstanceIdentifier.class);
    removed.add(protocolIid);
    ProtocolRemovedCommand protocolRemovedCommand = mock(ProtocolRemovedCommand.class, Mockito.CALLS_REAL_METHODS);
    MemberModifier.field(ProtocolRemovedCommand.class,"removed").set(protocolRemovedCommand, removed);

    MemberModifier.field(ProtocolRemovedCommand.class,"updatedBridges").set(protocolRemovedCommand, updatedBridges);
    when(updatedBridges.get(any(InstanceIdentifier.class))).thenReturn(mock(OvsdbBridgeAugmentation.class));

    Operations op = (Operations) setField("op");
    Mutate<GenericTableSchema> mutate = mock(Mutate.class);
    when(op.mutate(any(Bridge.class))).thenReturn(mutate);
    Column<GenericTableSchema, Set<String>> column = mock(Column.class);
    Bridge bridge = mock(Bridge.class);
    when(bridge.getProtocolsColumn()).thenReturn(column);
    when(column.getSchema()).thenReturn(mock(ColumnSchema.class));
    when(column.getData()).thenReturn(new HashSet<>());
    when(mutate.addMutation(any(ColumnSchema.class), any(Mutator.class), any(Set.class))).thenReturn(mutate);

    TransactionBuilder transaction = mock(TransactionBuilder.class);
    when(transaction.getTypedRowWrapper(any(Class.class))).thenReturn(bridge);

    protocolRemovedCommand.execute(transaction, bridgeOpState, mock(DataChangeEvent.class),
            mock(InstanceIdentifierCodec.class));
    Mockito.verify(transaction).add(any(Operation.class));
}
 
Example 6
Source File: DefaultLitePullConsumerTest.java    From rocketmq with Apache License 2.0 5 votes vote down vote up
@Before
public void init() throws Exception {
    PowerMockito.suppress(PowerMockito.method(DefaultLitePullConsumerImpl.class, "updateTopicSubscribeInfoWhenSubscriptionChanged"));
    Field field = MQClientInstance.class.getDeclaredField("rebalanceService");
    field.setAccessible(true);
    RebalanceService rebalanceService = (RebalanceService) field.get(mQClientFactory);
    field = RebalanceService.class.getDeclaredField("waitInterval");
    field.setAccessible(true);
    field.set(rebalanceService, 100);
}
 
Example 7
Source File: IPDeviceTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	// Suppress the 'readDeviceInfo' method of the parent class so that it is not
	// called from the child (IPDevice) class.
	PowerMockito.suppress(PowerMockito.method(AbstractXBeeDevice.class, "readDeviceInfo"));
	
	// Spy the IPDevice class.
	SerialPortRxTx mockPort = Mockito.mock(SerialPortRxTx.class);
	ipDevice = PowerMockito.spy(new IPDevice(mockPort));
	
	// Mock an IP address object.
	ipAddress = (Inet4Address) Inet4Address.getByAddress(RESPONSE_MY);
}
 
Example 8
Source File: IPv6DeviceTest.java    From xbee-java with Mozilla Public License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
	// Suppress the 'readDeviceInfo' method of the parent class so that it is not
	// called from the child (IPv6Device) class.
	PowerMockito.suppress(PowerMockito.method(AbstractXBeeDevice.class, "readDeviceInfo"));
	
	// Spy the IPv6Device class.
	SerialPortRxTx mockPort = Mockito.mock(SerialPortRxTx.class);
	ipv6Device = PowerMockito.spy(new IPv6Device(mockPort));
	
	// Mock an IPv6 address object.
	ipv6Address = (Inet6Address) Inet6Address.getByAddress(RESPONSE_MY);
}
 
Example 9
Source File: TestHiveMetadataProcessor.java    From datacollector with Apache License 2.0 5 votes vote down vote up
@Before
public void setup() throws Exception {
  // do not resolve JDBC URL
  PowerMockito.spy(HiveMetastoreUtil.class);

  // do not run Hive queries
  PowerMockito.suppress(
      MemberMatcher.method(
          HMSCache.class,
          "getOrLoad",
          HMSCacheType.class,
          String.class,
          HiveQueryExecutor.class
      )
  );
  // Do not create issues
  PowerMockito.suppress(
      MemberMatcher.method(
          HiveConfigBean.class,
          "init",
          Stage.Context.class,
          String.class,
          List.class
      )
  );
  PowerMockito.replace(
      MemberMatcher.method(
          HiveConfigBean.class,
          "getHiveConnection"
      )
  ).with((proxy, method, args) -> null);

  PowerMockito.replace(MemberMatcher.method(HiveQueryExecutor.class, "executeDescribeDatabase"))
      .with((proxy, method, args) -> "/user/hive/warehouse/" + args[0].toString() + ".db/");

}
 
Example 10
Source File: LocalDatabaseCreatorTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRegistryDatabaseWhenFileDoesNotExist() throws Exception {

    Mockito.when(file.exists()).thenReturn(false);
    Method method = PowerMockito.method(DatabaseCreator.class, "createRegistryDatabase");
    PowerMockito.suppress(method);
    localDatabaseCreator.createRegistryDatabase();
    Mockito.verify(file, Mockito.times(1)).exists();

}
 
Example 11
Source File: UtilsTest.java    From BetonQuest with GNU General Public License v3.0 5 votes vote down vote up
@Before
public void setUp() {
    PowerMockito.mockStatic(BetonQuest.class);
    BetonQuest betonQuestInstance = Mockito.mock(BetonQuest.class);
    PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(JavaPlugin.class));
    PowerMockito.when(BetonQuest.getInstance()).thenReturn(betonQuestInstance);
    PowerMockito.mockStatic(LogUtils.class);
    PowerMockito.when(LogUtils.getLogger()).thenReturn(Logger.getGlobal());
    PowerMockito.mockStatic(Config.class);
    PowerMockito.when(Config.getString("config.journal.lines_per_page")).thenReturn("13");
    PowerMockito.when(Config.getString("config.journal.chars_per_line")).thenReturn("19");

}
 
Example 12
Source File: LocalDatabaseCreatorTestCase.java    From carbon-apimgt with Apache License 2.0 5 votes vote down vote up
@Test
public void testCreateRegistryDatabaseWhenFileExists() throws Exception {

    Mockito.when(file.exists()).thenReturn(true);
    Method method = PowerMockito.method(DatabaseCreator.class, "createRegistryDatabase");
    PowerMockito.suppress(method);
    localDatabaseCreator.createRegistryDatabase();
    Mockito.verify(file, Mockito.times(1)).exists();
}
 
Example 13
Source File: TerminationPointUpdateCommandTest.java    From ovsdb with Eclipse Public License 1.0 4 votes vote down vote up
@SuppressWarnings({ "unchecked", "rawtypes" })
@Test
public void testUpdateTerminationPoint() throws Exception {
    TransactionBuilder transaction = mock(TransactionBuilder.class);
    BridgeOperationalState state = mock(BridgeOperationalState.class);
    OvsdbTerminationPointAugmentation terminationPoint = mock(OvsdbTerminationPointAugmentation.class);
    when(terminationPoint.getName()).thenReturn(TERMINATION_POINT_NAME);
    Node node = mock(Node.class);
    when(node.augmentation(OvsdbBridgeAugmentation.class)).thenReturn(mock(OvsdbBridgeAugmentation.class));
    Optional<Node> optNode = Optional.of(node);
    when(state.getBridgeNode(any(InstanceIdentifier.class))).thenReturn(optNode);

    // Test updateInterface()
    Interface ovsInterface = mock(Interface.class);
    when(transaction.getTypedRowWrapper(eq(Interface.class))).thenReturn(ovsInterface);

    Interface extraInterface = mock(Interface.class);
    when(transaction.getTypedRowWrapper(eq(Interface.class))).thenReturn(extraInterface);
    doNothing().when(extraInterface).setName(anyString());

    Operations op = OvsdbNodeUpdateCommandTest.setOpField();
    Update update = mock(Update.class);
    when(op.update(any(Interface.class))).thenReturn(update);

    Column<GenericTableSchema, String> column = mock(Column.class);
    when(extraInterface.getNameColumn()).thenReturn(column);
    ColumnSchema<GenericTableSchema, String> columnSchema = mock(ColumnSchema.class);
    when(column.getSchema()).thenReturn(columnSchema);
    when(columnSchema.opEqual(anyString())).thenReturn(mock(Condition.class));
    Where where = mock(Where.class);
    when(update.where(any(Condition.class))).thenReturn(where);
    when(where.build()).thenReturn(mock(Operation.class));
    when(transaction.add(any(Operation.class))).thenReturn(transaction);
    PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(TerminationPointCreateCommand.class));
    PowerMockito.suppress(MemberMatcher.methodsDeclaredIn(InstanceIdentifier.class));

    // Test updatePort()
    Port port = mock(Port.class);
    when(transaction.getTypedRowWrapper(eq(Port.class))).thenReturn(port);
    Port extraPort = mock(Port.class);
    when(transaction.getTypedRowWrapper(eq(Port.class))).thenReturn(extraPort);
    doNothing().when(extraPort).setName(anyString());
    when(op.update(any(Port.class))).thenReturn(update);
    when(extraPort.getNameColumn()).thenReturn(column);

    InstanceIdentifier<OvsdbTerminationPointAugmentation> iid = mock(InstanceIdentifier.class);
    terminationPointUpdateCommand.updateTerminationPoint(transaction, state, iid, terminationPoint,
            mock(InstanceIdentifierCodec.class));
    verify(transaction, times(1)).add(any(Operation.class));
}
 
Example 14
Source File: DeepSparkContextTest.java    From deep-spark with Apache License 2.0 4 votes vote down vote up
private DeepSparkContext createDeepSparkContext() {
    PowerMockito.suppress(PowerMockito.constructor(DeepSparkContext.class, SparkContext.class));
    return Whitebox.newInstance(DeepSparkContext.class);
}
 
Example 15
Source File: DatadogHttpClientTest.java    From flink with Apache License 2.0 4 votes vote down vote up
@Before
public void suppressValidateApiKey() {
	PowerMockito.suppress(MemberMatcher.method(DatadogHttpClient.class, "validateApiKey"));
}
 
Example 16
Source File: DefaultMQConsumerWithTraceTest.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Before
public void init() throws Exception {
    consumerGroup = "FooBarGroup" + System.currentTimeMillis();
    pushConsumer = new DefaultMQPushConsumer(consumerGroup, true, "");
    consumerGroupNormal = "FooBarGroup" + System.currentTimeMillis();
    normalPushConsumer = new DefaultMQPushConsumer(consumerGroupNormal, false, "");
    customTraceTopicpushConsumer = new DefaultMQPushConsumer(consumerGroup, true, customerTraceTopic);
    pushConsumer.setNamesrvAddr("127.0.0.1:9876");
    pushConsumer.setPullInterval(60 * 1000);

    asyncTraceDispatcher = (AsyncTraceDispatcher) pushConsumer.getTraceDispatcher();
    traceProducer = asyncTraceDispatcher.getTraceProducer();

    pushConsumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
            ConsumeConcurrentlyContext context) {
            return null;
        }
    });

    PowerMockito.suppress(PowerMockito.method(DefaultMQPushConsumerImpl.class, "updateTopicSubscribeInfoWhenSubscriptionChanged"));
    DefaultMQPushConsumerImpl pushConsumerImpl = pushConsumer.getDefaultMQPushConsumerImpl();
    rebalancePushImpl = spy(new RebalancePushImpl(pushConsumer.getDefaultMQPushConsumerImpl()));
    Field field = DefaultMQPushConsumerImpl.class.getDeclaredField("rebalanceImpl");
    field.setAccessible(true);
    field.set(pushConsumerImpl, rebalancePushImpl);
    pushConsumer.subscribe(topic, "*");

    pushConsumer.start();

    mQClientFactory = spy(pushConsumerImpl.getmQClientFactory());
    mQClientTraceFactory = spy(pushConsumerImpl.getmQClientFactory());

    field = DefaultMQPushConsumerImpl.class.getDeclaredField("mQClientFactory");
    field.setAccessible(true);
    field.set(pushConsumerImpl, mQClientFactory);

    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mQClientFactory, mQClientAPIImpl);

    Field fieldTrace = DefaultMQProducerImpl.class.getDeclaredField("mQClientFactory");
    fieldTrace.setAccessible(true);
    fieldTrace.set(traceProducer.getDefaultMQProducerImpl(), mQClientTraceFactory);

    fieldTrace = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    fieldTrace.setAccessible(true);
    fieldTrace.set(mQClientTraceFactory, mQClientTraceAPIImpl);

    pullAPIWrapper = spy(new PullAPIWrapper(mQClientFactory, consumerGroup, false));
    field = DefaultMQPushConsumerImpl.class.getDeclaredField("pullAPIWrapper");
    field.setAccessible(true);
    field.set(pushConsumerImpl, pullAPIWrapper);

    pushConsumer.getDefaultMQPushConsumerImpl().getRebalanceImpl().setmQClientFactory(mQClientFactory);
    mQClientFactory.registerConsumer(consumerGroup, pushConsumerImpl);

    when(mQClientFactory.getMQClientAPIImpl().pullMessage(anyString(), any(PullMessageRequestHeader.class),
        anyLong(), any(CommunicationMode.class), nullable(PullCallback.class)))
        .thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                PullMessageRequestHeader requestHeader = mock.getArgument(1);
                MessageClientExt messageClientExt = new MessageClientExt();
                messageClientExt.setTopic(topic);
                messageClientExt.setQueueId(0);
                messageClientExt.setMsgId("123");
                messageClientExt.setBody(new byte[] {'a'});
                messageClientExt.setOffsetMsgId("234");
                messageClientExt.setBornHost(new InetSocketAddress(8080));
                messageClientExt.setStoreHost(new InetSocketAddress(8080));
                PullResult pullResult = createPullResult(requestHeader, PullStatus.FOUND, Collections.<MessageExt>singletonList(messageClientExt));
                ((PullCallback) mock.getArgument(4)).onSuccess(pullResult);
                return pullResult;
            }
        });

    doReturn(new FindBrokerResult("127.0.0.1:10911", false)).when(mQClientFactory).findBrokerAddressInSubscribe(anyString(), anyLong(), anyBoolean());
    Set<MessageQueue> messageQueueSet = new HashSet<MessageQueue>();
    messageQueueSet.add(createPullRequest().getMessageQueue());
    pushConsumer.getDefaultMQPushConsumerImpl().updateTopicSubscribeInfo(topic, messageQueueSet);
}
 
Example 17
Source File: DefaultMQPushConsumerTest.java    From rocketmq with Apache License 2.0 4 votes vote down vote up
@Before
public void init() throws Exception {
    consumerGroup = "FooBarGroup" + System.currentTimeMillis();
    pushConsumer = new DefaultMQPushConsumer(consumerGroup);
    pushConsumer.setNamesrvAddr("127.0.0.1:9876");
    pushConsumer.setPullInterval(60 * 1000);

    pushConsumer.registerMessageListener(new MessageListenerConcurrently() {
        @Override
        public ConsumeConcurrentlyStatus consumeMessage(List<MessageExt> msgs,
            ConsumeConcurrentlyContext context) {
            return null;
        }
    });

    DefaultMQPushConsumerImpl pushConsumerImpl = pushConsumer.getDefaultMQPushConsumerImpl();
    PowerMockito.suppress(PowerMockito.method(DefaultMQPushConsumerImpl.class, "updateTopicSubscribeInfoWhenSubscriptionChanged"));
    rebalancePushImpl = spy(new RebalancePushImpl(pushConsumer.getDefaultMQPushConsumerImpl()));
    Field field = DefaultMQPushConsumerImpl.class.getDeclaredField("rebalanceImpl");
    field.setAccessible(true);
    field.set(pushConsumerImpl, rebalancePushImpl);

    pushConsumer.subscribe(topic, "*");
    pushConsumer.start();

    mQClientFactory = spy(pushConsumerImpl.getmQClientFactory());
    field = DefaultMQPushConsumerImpl.class.getDeclaredField("mQClientFactory");
    field.setAccessible(true);
    field.set(pushConsumerImpl, mQClientFactory);

    field = MQClientInstance.class.getDeclaredField("mQClientAPIImpl");
    field.setAccessible(true);
    field.set(mQClientFactory, mQClientAPIImpl);

    pullAPIWrapper = spy(new PullAPIWrapper(mQClientFactory, consumerGroup, false));
    field = DefaultMQPushConsumerImpl.class.getDeclaredField("pullAPIWrapper");
    field.setAccessible(true);
    field.set(pushConsumerImpl, pullAPIWrapper);

    pushConsumer.getDefaultMQPushConsumerImpl().getRebalanceImpl().setmQClientFactory(mQClientFactory);
    mQClientFactory.registerConsumer(consumerGroup, pushConsumerImpl);

    when(mQClientFactory.getMQClientAPIImpl().pullMessage(anyString(), any(PullMessageRequestHeader.class),
        anyLong(), any(CommunicationMode.class), nullable(PullCallback.class)))
        .thenAnswer(new Answer<Object>() {
            @Override
            public Object answer(InvocationOnMock mock) throws Throwable {
                PullMessageRequestHeader requestHeader = mock.getArgument(1);
                MessageClientExt messageClientExt = new MessageClientExt();
                messageClientExt.setTopic(topic);
                messageClientExt.setQueueId(0);
                messageClientExt.setMsgId("123");
                messageClientExt.setBody(new byte[] {'a'});
                messageClientExt.setOffsetMsgId("234");
                messageClientExt.setBornHost(new InetSocketAddress(8080));
                messageClientExt.setStoreHost(new InetSocketAddress(8080));
                PullResult pullResult = createPullResult(requestHeader, PullStatus.FOUND, Collections.<MessageExt>singletonList(messageClientExt));
                ((PullCallback) mock.getArgument(4)).onSuccess(pullResult);
                return pullResult;
            }
        });

    doReturn(new FindBrokerResult("127.0.0.1:10911", false)).when(mQClientFactory).findBrokerAddressInSubscribe(anyString(), anyLong(), anyBoolean());
    doReturn(Collections.singletonList(mQClientFactory.getClientId())).when(mQClientFactory).findConsumerIdList(anyString(), anyString());
    Set<MessageQueue> messageQueueSet = new HashSet<MessageQueue>();
    messageQueueSet.add(createPullRequest().getMessageQueue());
    pushConsumer.getDefaultMQPushConsumerImpl().updateTopicSubscribeInfo(topic, messageQueueSet);
    doReturn(123L).when(rebalancePushImpl).computePullFromWhere(any(MessageQueue.class));
}
 
Example 18
Source File: TransferListenerTest.java    From ibm-cos-sdk-java with Apache License 2.0 4 votes vote down vote up
@Before
   public void setup(){
	PowerMockito.mockStatic(ITransferListener.class);

	PowerMockito.suppress(PowerMockito.defaultConstructorIn(ITransferListener.class));
}
 
Example 19
Source File: OvsdbPortUpdateCommandTest.java    From ovsdb with Eclipse Public License 1.0 4 votes vote down vote up
@Test
@SuppressWarnings("unchecked")
public void testUpdateTerminationPoints() throws Exception {
    portUpdatedRows = new HashMap<>();
    Port port = mock(Port.class);
    UUID uuid = mock(UUID.class);
    portUpdatedRows.put(uuid, port);
    field(OvsdbPortUpdateCommand.class, "portUpdatedRows").set(ovsdbPortUpdateCommand, portUpdatedRows);
    Column<GenericTableSchema, String> bridgeColumn = mock(Column.class);
    when(port.getNameColumn()).thenReturn(bridgeColumn);
    when(bridgeColumn.getData()).thenReturn(TERMINATION_POINT_NAME);

    InstanceIdentifier<Node> nodeIid = InstanceIdentifier.create(NetworkTopology.class)
            .child(Topology.class, new TopologyKey(SouthboundConstants.OVSDB_TOPOLOGY_ID))
            .child(Node.class, new NodeKey(new NodeId("nodeId")));

    Optional<InstanceIdentifier<Node>> bridgeIid = Optional.of(nodeIid);
    PowerMockito.doReturn(bridgeIid).when(ovsdbPortUpdateCommand, "getTerminationPointBridge", any(UUID.class));

    NodeId bridgeId = mock(NodeId.class);
    PowerMockito.mockStatic(SouthboundMapper.class);
    PowerMockito.when(SouthboundMapper.createManagedNodeId(any(InstanceIdentifier.class))).thenReturn(bridgeId);

    PowerMockito.whenNew(TpId.class).withAnyArguments().thenReturn(mock(TpId.class));
    TerminationPointKey tpKey = mock(TerminationPointKey.class);
    PowerMockito.whenNew(TerminationPointKey.class).withAnyArguments().thenReturn(tpKey);
    TerminationPointBuilder tpBuilder = mock(TerminationPointBuilder.class);
    PowerMockito.whenNew(TerminationPointBuilder.class).withNoArguments().thenReturn(tpBuilder);
    when(tpBuilder.withKey(any(TerminationPointKey.class))).thenReturn(tpBuilder);
    when(tpKey.getTpId()).thenReturn(mock(TpId.class));
    when(tpBuilder.setTpId(any(TpId.class))).thenReturn(tpBuilder);
    InstanceIdentifier<TerminationPoint> tpPath = mock(InstanceIdentifier.class);
    PowerMockito.doReturn(tpPath).when(ovsdbPortUpdateCommand, "getInstanceIdentifier",
            any(InstanceIdentifier.class), any(Port.class));

    OvsdbTerminationPointAugmentationBuilder tpAugmentationBuilder = mock(
            OvsdbTerminationPointAugmentationBuilder.class);
    PowerMockito.whenNew(OvsdbTerminationPointAugmentationBuilder.class).withNoArguments()
            .thenReturn(tpAugmentationBuilder);
    PowerMockito.suppress(MemberMatcher.method(OvsdbPortUpdateCommand.class, "buildTerminationPoint",
            ReadWriteTransaction.class, InstanceIdentifier.class, OvsdbTerminationPointAugmentationBuilder.class,
            Node.class, Entry.class));

    Column<GenericTableSchema, Set<UUID>> interfacesColumn = mock(Column.class);
    when(port.getInterfacesColumn()).thenReturn(interfacesColumn);
    Set<UUID> uuids = new HashSet<>();
    UUID uuid2 = mock(UUID.class);
    uuids.add(uuid2);
    when(interfacesColumn.getData()).thenReturn(uuids);

    ifUpdatedRows = new HashMap<>();
    interfaceOldRows = new HashMap<>();
    Interface iface = mock(Interface.class);
    ifUpdatedRows.put(uuid2, iface);
    Interface interfaceUpdate = mock(Interface.class);
    ifUpdatedRows.put(uuid, interfaceUpdate);
    interfaceOldRows.put(uuid2, iface);
    field(OvsdbPortUpdateCommand.class, "interfaceUpdatedRows").set(ovsdbPortUpdateCommand, ifUpdatedRows);
    field(OvsdbPortUpdateCommand.class, "interfaceOldRows").set(ovsdbPortUpdateCommand, interfaceOldRows);
    PowerMockito.suppress(MemberMatcher.method(OvsdbPortUpdateCommand.class, "buildTerminationPoint",
            OvsdbTerminationPointAugmentationBuilder.class, Interface.class));

    when(tpAugmentationBuilder.build()).thenReturn(mock(OvsdbTerminationPointAugmentation.class));
    when(tpBuilder.addAugmentation(eq(OvsdbTerminationPointAugmentation.class),
            any(OvsdbTerminationPointAugmentation.class))).thenReturn(tpBuilder);
    when(tpBuilder.build()).thenReturn(mock(TerminationPoint.class));
    portOldRows = new HashMap<>();
    portOldRows.put(uuid, port);
    MemberModifier.field(OvsdbPortUpdateCommand.class, "portOldRows").set(ovsdbPortUpdateCommand, portOldRows);
    ReadWriteTransaction transaction = mock(ReadWriteTransaction.class);
    doNothing().when(transaction).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
            any(TerminationPoint.class));
    doNothing().when(transaction).put(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
            any(TerminationPoint.class));

    Column<GenericTableSchema, String> interfaceColumn = mock(Column.class);
    when(interfaceUpdate.getNameColumn()).thenReturn(interfaceColumn);
    when(interfaceColumn.getData()).thenReturn(INTERFACE_NAME);
    when(ovsdbPortUpdateCommand.getOvsdbConnectionInstance()).thenReturn(mock(OvsdbConnectionInstance.class));

    PowerMockito.doReturn(bridgeIid).when(ovsdbPortUpdateCommand, "getTerminationPointBridge",
            any(ReadWriteTransaction.class), any(Node.class), anyString());
    PowerMockito.when(SouthboundMapper.createManagedNodeId(any(InstanceIdentifier.class))).thenReturn(bridgeId);
    PowerMockito.whenNew(TopologyKey.class).withAnyArguments().thenReturn(mock(TopologyKey.class));
    PowerMockito.whenNew(NodeKey.class).withAnyArguments().thenReturn(mock(NodeKey.class));

    Node node = mock(Node.class);
    Whitebox.invokeMethod(ovsdbPortUpdateCommand, "updateTerminationPoints", transaction, node);
    verify(ovsdbPortUpdateCommand).getInstanceIdentifier(any(InstanceIdentifier.class),
        any(Port.class));
    verify(transaction, times(2)).merge(any(LogicalDatastoreType.class), any(InstanceIdentifier.class),
            any(TerminationPoint.class));
}
 
Example 20
Source File: PowerMockTest.java    From Awesome-WanAndroid with Apache License 2.0 4 votes vote down vote up
@Test
public void skipPrivateMethod() {
    Banana banana = new Banana();
    PowerMockito.suppress(PowerMockito.method(Banana.class, "flavor"));
    System.out.println(banana.getBananaInfo());
}