--- /dev/null
+/*
+ * Copyright 2005-2010 the original author or authors.
+ *
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ */
+package org.wamblee.general;
+
+import static junit.framework.Assert.*;
+import static org.mockito.Matchers.*;
+import static org.mockito.Mockito.*;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.general.ThreadSpecificProxyFactory;
+
+public class ThreadSpecificProxyFactoryTest {
+
+ private static interface Service {
+ int execute(int aX) throws Exception;
+ }
+
+ private ThreadSpecificProxyFactory<Service> factory;
+ private Service proxy;
+
+ @Before
+ public void setUp() {
+ factory = new ThreadSpecificProxyFactory<Service>(Service.class);
+ proxy = factory.getProxy();
+ }
+
+ @After
+ public void tearDown() {
+ // Empty.
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void testNoSvcDefined() throws Exception {
+ proxy.execute(10);
+ }
+
+ @Test
+ public void testInvokeThroughProxy() throws Exception {
+ Service svc = mock(Service.class);
+ when(svc.execute(anyInt())).thenReturn(50);
+ factory.set(svc);
+ assertEquals(50, proxy.execute(10));
+ verify(svc).execute(10);
+ }
+
+ @Test
+ public void testInvokeThroughProxyWithException() throws Exception {
+ Service svc = mock(Service.class);
+ try {
+ when(svc.execute(anyInt())).thenThrow(
+ new RuntimeException("exception thrown"));
+ factory.set(svc);
+ svc.execute(10);
+ fail();
+ } catch (RuntimeException e) {
+ assertEquals("exception thrown", e.getMessage());
+ }
+ }
+
+ private int returnFromThread;
+
+ @Test
+ public void testVerifyThreadSpecificUsingTwoThreads() throws Exception {
+ Service svc1 = mock(Service.class);
+ final Service svc2 = mock(Service.class);
+ when(svc1.execute(anyInt())).thenReturn(10);
+ when(svc2.execute(anyInt())).thenReturn(20);
+
+ factory.set(svc1);
+ assertEquals(10, svc1.execute(10));
+ Thread t = new Thread() {
+ public void run() {
+ factory.set(svc2);
+ try {
+ returnFromThread = proxy.execute(100);
+ } catch (Exception e) {
+ returnFromThread = 100000;
+ }
+ };
+ };
+ t.start();
+ t.join();
+ assertEquals(20, returnFromThread);
+ assertEquals(10, proxy.execute(100));
+
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testNotAnInterface() {
+ ThreadSpecificProxyFactory f = new ThreadSpecificProxyFactory(String.class);
+ }
+}