1
2
3
4 package com.github.smokestack.jpa;
5
6 import java.util.ArrayList;
7 import java.util.List;
8 import java.util.Map;
9
10 import javax.persistence.EntityManager;
11 import javax.persistence.EntityManagerFactory;
12
13 import org.apache.commons.lang.builder.ReflectionToStringBuilder;
14 import org.apache.commons.lang.builder.ToStringStyle;
15 import org.hamcrest.core.Is;
16 import static org.hamcrest.MatcherAssert.assertThat;
17
18
19
20
21
22 public class MockEntityManagerFactory implements EntityManagerFactory {
23
24 public enum EMFactoryState {NEW, CLOSE};
25
26 protected EMFactoryState mockState=EMFactoryState.NEW;
27
28 protected List<MockEntityManager> mockEntityManagers=new ArrayList<MockEntityManager>();
29
30
31
32
33 public MockEntityManagerFactory() {
34 }
35
36
37
38
39 public void close() {
40 assertThat("mockState", mockState, Is.is(EMFactoryState.NEW));
41 _close();
42 mockState=EMFactoryState.CLOSE;
43 }
44
45 public void _close() {
46 }
47
48
49
50 public EntityManager createEntityManager() {
51 assertThat("mockState", mockState, Is.is(EMFactoryState.NEW));
52 _createEntityManager();
53 MockEntityManager em=new MockEntityManager();
54 mockEntityManagers.add(em);
55 return em;
56 }
57
58 public EntityManager _createEntityManager() {
59 return null;
60 }
61
62
63
64 public EntityManager createEntityManager(Map map) {
65 assertThat("mockState", mockState, Is.is(EMFactoryState.NEW));
66 _createEntityManager(map);
67 MockEntityManager em=new MockEntityManager(map);
68 mockEntityManagers.add(em);
69 return em;
70 }
71
72 public EntityManager _createEntityManager(Map map) {
73 return null;
74 }
75
76
77
78 public boolean isOpen() {
79 _isOpen();
80 return EMFactoryState.NEW==mockState;
81 }
82
83 public boolean _isOpen() {
84 return false;
85 }
86
87
88
89 public String toString(){
90 return ReflectionToStringBuilder.toString(this, ToStringStyle.MULTI_LINE_STYLE);
91 }
92
93
94
95
96 public void assertMockComplete() {
97 assertThat("mockState", mockState, Is.is(EMFactoryState.CLOSE));
98 for (MockEntityManager em: mockEntityManagers){
99 em.assertMockComplete();
100 }
101 }
102
103
104
105
106 public void assertMockCommit() {
107 assertThat("mockState", mockState, Is.is(EMFactoryState.CLOSE));
108 for (MockEntityManager em: mockEntityManagers){
109 em.assertMockCommit();
110 }
111 }
112
113
114
115
116 public void assertMockRollback() {
117 assertThat("mockState", mockState, Is.is(EMFactoryState.CLOSE));
118 for (MockEntityManager em: mockEntityManagers){
119 em.assertMockRollback();
120 }
121 }
122
123 public EMFactoryState getMockState() {
124 return mockState;
125 }
126 }