CliTrigger implements AutoCloseable { private VirtualNetwork getVirtualNetwork(UserId userId) { VirtualNetworkId virtualNetworkId = new VirtualNetworkId(userId.getValue()); VirtualNetworkKey virtualNetworkKey = new VirtualNetworkKey(virtualNetworkId); ReadOnlyTransaction readOnlyTransaction = dataProvider.newReadOnlyTransaction(); InstanceIdentifier<VirtualNetwork> virtualNetworkIid = InstanceIdentifier .builder(VirtualNetworks.class) .child(VirtualNetwork.class, virtualNetworkKey) .build(); Optional<VirtualNetwork> result = null; try { result = readOnlyTransaction.read(LogicalDatastoreType.CONFIGURATION, virtualNetworkIid).get(); } catch (Exception e) { LOG.error("Exception:",e); } if (result.isPresent()) { LOG.info("getVirtualNetwork OK"); return result.get(); }else{ LOG.info("getVirtualNetwork ERROR"); return null; } } CliTrigger(DataBroker dataProvider); @Override void close();  }
@Test public void testGetVirtualNetwork() throws Exception{ Class<CliTrigger> class1 = CliTrigger.class; Method method = class1.getDeclaredMethod("getVirtualNetwork", new Class[]{UserId.class}); method.setAccessible(true); UserId userId = mock(UserId.class); VirtualNetwork result; ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class); CheckedFuture checkedFuture = mock(CheckedFuture.class); Optional<VirtualNetwork> optional = mock(Optional.class); when(userId.getValue()).thenReturn(new String("00001111-0000-0000-0000-000011112222")); when(dataBroker.newReadOnlyTransaction()).thenReturn(readOnlyTransaction); when(readOnlyTransaction.read(any(LogicalDatastoreType.class), any(InstanceIdentifier.class))).thenReturn(checkedFuture); when(checkedFuture.get()).thenReturn(optional); when(optional.isPresent()) .thenReturn(false) .thenReturn(true); when(optional.get()).thenReturn(mock(VirtualNetwork.class)); result = (VirtualNetwork) method.invoke(cliTrigger,userId); Assert.assertTrue(result == null); result = (VirtualNetwork) method.invoke(cliTrigger,userId); Assert.assertTrue(result != null); verify(optional).get(); verify(optional,times(2)).isPresent(); }