+/*
+ * 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.support.persistence;
+
+import javax.persistence.EntityManager;
+
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.wamblee.support.persistence.JpaBuilder.JpaUnitOfWork;
+
+import static junit.framework.TestCase.*;
+import static org.mockito.Mockito.*;
+
+public class TransactionProxyFactoryTestBase {
+
+ public static interface Service {
+ int execute(int aValue) throws Exception;
+ }
+
+ private JpaTester jpaTester;
+
+ @Before
+ public void setUp() throws Exception {
+ jpaTester = new JpaTester(new MyPersistenceUnit());
+ jpaTester.start();
+ }
+
+ @After
+ public void tearDown() throws Exception {
+ jpaTester.stop();
+ }
+
+ @Test
+ public void testServiceIsInvoked() throws Exception {
+ TransactionProxyFactory<Service> factory = new TransactionProxyFactory<Service>(
+ jpaTester.getJpaBuilder(), Service.class);
+ Service service = mock(Service.class);
+ when(service.execute(10)).thenReturn(200);
+ Service proxy = factory.getProxy(service);
+ int res = proxy.execute(10);
+ assertEquals(200, res);
+ verify(service).execute(10);
+ }
+
+ @Test
+ public void testServiceThrowsException() throws Exception {
+ TransactionProxyFactory<Service> factory = new TransactionProxyFactory<Service>(
+ jpaTester.getJpaBuilder(), Service.class);
+ Service service = mock(Service.class);
+ when(service.execute(10)).thenThrow(new RuntimeException("xyz"));
+ Service proxy = factory.getProxy(service);
+ try {
+ int res = proxy.execute(10);
+ fail();
+ } catch (RuntimeException e) {
+ assertEquals("xyz", e.getMessage());
+ }
+ }
+
+ @Test
+ public void testEntityManagerIsPassed() throws Exception {
+
+
+ final TransactionProxyFactory<Service> factory = new TransactionProxyFactory<Service>(
+ jpaTester.getJpaBuilder(), Service.class);
+ Service service = new Service() {
+ private EntityManager em = factory.getTransactionScopedEntityManager();
+
+ @Override
+ public int execute(int aValue) throws Exception {
+ assertNotNull(em);
+ assertTrue(em.isOpen());
+ return 0;
+ }
+ };
+
+ final Service proxy = factory.getProxy(service);
+ jpaTester.getJpaBuilder().execute(new JpaUnitOfWork<Void>() {
+ @Override
+ public Void execute(EntityManager aEm) throws Exception {
+ assert(aEm != null);
+ proxy.execute(10);
+ return null;
+ }
+ });
+ }
+
+}