• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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 static org.hamcrest.Matchers.is;
20 import static org.junit.Assert.assertThat;
21 import static org.mockito.Mockito.doThrow;
22 import static org.mockito.Mockito.mock;
23 import static org.mockito.Mockito.when;
24 
25 import java.util.Properties;
26 import javax.persistence.EntityManager;
27 import javax.persistence.EntityManagerFactory;
28 import javax.persistence.spi.PersistenceProvider;
29 import junit.framework.TestCase;
30 
31 public class JpaPersistServiceTest extends TestCase {
32 
33   private static final String PERSISTENCE_UNIT_NAME = "test_persistence_unit_name";
34   private static final Properties PERSISTENCE_PROPERTIES = new Properties();
35 
36   private final JpaPersistService sut =
37       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))
45         .thenReturn(factory);
46     when(factory.createEntityManager()).thenReturn(entityManager);
47   }
48 
test_givenErrorOnEntityManagerClose_whenEndIsCalled_thenEntityManagerIsRemoved()49   public void test_givenErrorOnEntityManagerClose_whenEndIsCalled_thenEntityManagerIsRemoved() {
50     sut.start(factory);
51     sut.begin();
52 
53     // arrange an exception on sut.end(), which invokes entityManager.close()
54     doThrow(SimulatedException.class).when(entityManager).close();
55     try {
56       sut.end();
57       fail("Exception expected");
58     } catch (SimulatedException expected) {
59       assertThat(sut.isWorking(), is(false));
60     }
61   }
62 
63   private static class SimulatedException extends RuntimeException {}
64 }
65