1 /** 2 * Copyright (C) 2014 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 17 package com.google.inject.persist.jpa; 18 19 import junit.framework.TestCase; 20 import static org.hamcrest.Matchers.is; 21 import static org.junit.Assert.assertThat; 22 import static org.mockito.Mockito.doThrow; 23 import static org.mockito.Mockito.mock; 24 import static org.mockito.Mockito.when; 25 26 import java.util.Properties; 27 28 import javax.persistence.EntityManager; 29 import javax.persistence.EntityManagerFactory; 30 import javax.persistence.spi.PersistenceProvider; 31 32 public class JpaPersistServiceTest extends TestCase { 33 34 private static final String PERSISTENCE_UNIT_NAME = "test_persistence_unit_name"; 35 private static final Properties PERSISTENCE_PROPERTIES = new Properties(); 36 37 private final JpaPersistService sut = new JpaPersistService(PERSISTENCE_UNIT_NAME, PERSISTENCE_PROPERTIES); 38 private final PersistenceProvider provider = mock(PersistenceProvider.class); 39 private final EntityManagerFactory factory = mock(EntityManagerFactory.class); 40 private final EntityManager entityManager = mock(EntityManager.class); 41 42 @Override setUp()43 public void setUp() throws Exception { 44 when(provider.createEntityManagerFactory(PERSISTENCE_UNIT_NAME, PERSISTENCE_PROPERTIES)).thenReturn(factory); 45 when(factory.createEntityManager()).thenReturn(entityManager); 46 } 47 test_givenErrorOnEntityManagerClose_whenEndIsCalled_thenEntityManagerIsRemoved()48 public void test_givenErrorOnEntityManagerClose_whenEndIsCalled_thenEntityManagerIsRemoved() { 49 sut.start(factory); 50 sut.begin(); 51 52 // arrange an exception on sut.end(), which invokes entityManager.close() 53 doThrow(SimulatedException.class).when(entityManager).close(); 54 try { 55 sut.end(); 56 fail("Exception expected"); 57 } 58 catch (SimulatedException expected) { 59 assertThat(sut.isWorking(), is(false)); 60 } 61 } 62 63 private class SimulatedException extends RuntimeException { 64 } 65 } 66