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