CliTrigger implements AutoCloseable { private PhysicalNetwork getPhysicalNetwork() { ReadOnlyTransaction readOnlyTransaction = dataProvider.newReadOnlyTransaction(); InstanceIdentifier<PhysicalNetwork> physicalNetworkIid = InstanceIdentifier .builder(PhysicalNetwork.class) .build(); Optional<PhysicalNetwork> result = null; try { result = readOnlyTransaction.read(LogicalDatastoreType.OPERATIONAL, physicalNetworkIid).get(); } catch (Exception e) { LOG.error("Exception:",e); } if (result.isPresent()) { LOG.info("getPhysicalNetwork OK"); return result.get(); }else{ LOG.info("getPhysicalNetwork ERROR"); return null; } } CliTrigger(DataBroker dataProvider); @Override void close();  }
@Test public void testGetPhysicalNetwork() throws Exception{ Class<CliTrigger> class1 = CliTrigger.class; Method method = class1.getDeclaredMethod("getPhysicalNetwork"); method.setAccessible(true); ReadOnlyTransaction readOnlyTransaction = mock(ReadOnlyTransaction.class); CheckedFuture checkedFuture = mock(CheckedFuture.class); Optional<PhysicalNetwork> optional = mock(Optional.class); PhysicalNetwork result; 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(PhysicalNetwork.class)); result = (PhysicalNetwork) method.invoke(cliTrigger); Assert.assertTrue(result == null); result = (PhysicalNetwork) method.invoke(cliTrigger); Assert.assertTrue(result != null); verify(optional).get(); verify(optional, times(2)).isPresent(); }