1/** 2 * Copyright (C) 2010 Google, Inc. 3 * 4 * Licensed under the Apache License, Version 2.0 (the "License"); 5 * you may not use this file except in compliance with the License. 6 * You may obtain a copy of the License at 7 * 8 * http://www.apache.org/licenses/LICENSE-2.0 9 * 10 * Unless required by applicable law or agreed to in writing, software 11 * distributed under the License is distributed on an "AS IS" BASIS, 12 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13 * See the License for the specific language governing permissions and 14 * limitations under the License. 15 */ 16 17package com.google.inject.persist.jpa; 18 19import com.google.inject.Guice; 20import com.google.inject.Inject; 21import com.google.inject.Injector; 22import com.google.inject.persist.PersistService; 23import com.google.inject.persist.Transactional; 24 25import junit.framework.TestCase; 26 27import java.util.Date; 28 29import javax.persistence.EntityManager; 30import javax.persistence.PersistenceException; 31 32/** 33 * @author Dhanji R. Prasanna (dhanji@gmail.com) 34 */ 35 36public class ManualLocalTransactionsConfidenceTest extends TestCase { 37 private Injector injector; 38 private static final String UNIQUE_TEXT_3 = 39 ManualLocalTransactionsConfidenceTest.class.getSimpleName() 40 + "CONSTRAINT_VIOLATING some other unique text" + new Date(); 41 42 @Override 43 public void setUp() { 44 injector = Guice.createInjector(new JpaPersistModule("testUnit")); 45 46 //startup persistence 47 injector.getInstance(PersistService.class).start(); 48 } 49 50 @Override 51 public final void tearDown() { 52 injector.getInstance(PersistService.class).stop(); 53 } 54 55 public void testThrowingCleanupInterceptorConfidence() { 56 Exception e = null; 57 try { 58 System.out.println( 59 "\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********"); 60 injector.getInstance(TransactionalObject.class).runOperationInTxn(); 61 fail(); 62 } catch (RuntimeException re) { 63 e = re; 64 System.out.println( 65 "\n\n******************************* EXPECTED EXCEPTION NORMAL TEST BEHAVIOR **********"); 66 re.printStackTrace(System.out); 67 System.out.println( 68 "\n\n**********************************************************************************"); 69 } 70 71 assertNotNull("No exception was thrown!", e); 72 assertTrue("Exception thrown was not what was expected (i.e. commit-time)", 73 e instanceof PersistenceException); 74 } 75 76 public static class TransactionalObject { 77 @Inject EntityManager em; 78 79 @Transactional 80 public void runOperationInTxn() { 81 JpaParentTestEntity entity = new JpaParentTestEntity(); 82 JpaTestEntity child = new JpaTestEntity(); 83 84 child.setText(UNIQUE_TEXT_3); 85 em.persist(child); 86 87 entity.getChildren().add(child); 88 em.persist(entity); 89 90 entity = new JpaParentTestEntity(); 91 entity.getChildren().add(child); 92 em.persist(entity); 93 } 94 } 95} 96