SyncClientAdapterHandler implements InvocationHandler { public static <S, A> S newHandler(Class<? extends S> syncIfcClass, Class<? super A> asyncIfcClass, A delegateAdapter) { SyncClientAdapterHandler handler = new SyncClientAdapterHandler(asyncIfcClass, delegateAdapter); Class<?>[] ifcClasses = new Class<?>[]{syncIfcClass}; return syncIfcClass.cast(Proxy.newProxyInstance(syncIfcClass.getClassLoader(), ifcClasses, handler)); } private  SyncClientAdapterHandler(Class<?> asyncIfcClass, Object delegate); static S newHandler(Class<? extends S> syncIfcClass, Class<? super A> asyncIfcClass,
                                      A delegateAdapter); @Override Object invoke(Object proxy, Method method, Object[] args);  }
@Test public void testHandleAsyncResult() { DeepThoughtSync sync = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtAsync.class, createAsync()); assertThat(sync.answerQuestionOfLifeUniverseAndEverything()).isEqualTo(ANSWER); }
@Test public void testHandleSyncResult() { DeepThoughtSync syncDelegate = () -> ANSWER; DeepThoughtSync sync = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtSync.class, syncDelegate); assertThat(sync.answerQuestionOfLifeUniverseAndEverything()).isEqualTo(ANSWER); }
@Test public void testHandleUnexpectedMethod() { DeepThoughtSync sync = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, Object.class, new Object()); try { sync.answerQuestionOfLifeUniverseAndEverything(); fail("No exception thrown."); } catch (UndeclaredThrowableException e) { assertThat(e.getCause()).isInstanceOf(NoSuchMethodException.class); } }
@Test public void testHandleEqualsTrue() { DeepThoughtAsync async = createAsync(); DeepThoughtSync sync1 = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtAsync.class, async); DeepThoughtSync sync2 = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtAsync.class, async); assertThat(sync1).isEqualTo(sync2); }
@Test public void testHandleEqualsFalse() { DeepThoughtSync sync1 = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtAsync.class, createAsync()); DeepThoughtAsync otherAsync = () -> CompletableFuture.completedFuture(ANSWER - 1); DeepThoughtSync sync2 = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtAsync.class, otherAsync); assertThat(sync1).isNotEqualTo(sync2); }
@Test public void testHandleEqualsOtherObject() { DeepThoughtSync sync = SyncClientAdapterHandler.newHandler(DeepThoughtSync.class, DeepThoughtAsync.class, createAsync()); assertThat(sync).isNotEqualTo(new Object()); }