Skip to content

Commit 2914aa4

Browse files
authored
Merge pull request #1314 from mherman22/DictionaryTest
(test) Add tests for the Dictionary Service methods
2 parents 9d1c280 + 175987e commit 2914aa4

File tree

5 files changed

+375
-29
lines changed

5 files changed

+375
-29
lines changed

pom.xml

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -401,6 +401,12 @@
401401
<version>${springframework.version}</version>
402402
<scope>test</scope>
403403
</dependency>
404+
<dependency>
405+
<groupId>org.dbunit</groupId>
406+
<artifactId>dbunit</artifactId>
407+
<version>2.7.3</version>
408+
<scope>test</scope>
409+
</dependency>
404410
<dependency>
405411
<groupId>org.mockito</groupId>
406412
<artifactId>mockito-core</artifactId>

src/test/java/org/openelisglobal/BaseWebContextSensitiveTest.java

Lines changed: 136 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -4,31 +4,59 @@
44
import com.fasterxml.jackson.databind.DeserializationFeature;
55
import com.fasterxml.jackson.databind.ObjectMapper;
66
import java.io.IOException;
7-
import org.junit.runner.RunWith;
7+
import java.io.InputStream;
8+
import java.util.*;
9+
import javax.sql.DataSource;
10+
import org.dbunit.database.DatabaseConfig;
11+
import org.dbunit.database.DatabaseConnection;
12+
import org.dbunit.database.IDatabaseConnection;
13+
import org.dbunit.dataset.IDataSet;
14+
import org.dbunit.dataset.xml.FlatXmlDataSet;
15+
import org.dbunit.operation.DatabaseOperation;
816
import org.springframework.beans.factory.annotation.Autowired;
917
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
1018
import org.springframework.test.context.ActiveProfiles;
1119
import org.springframework.test.context.ContextConfiguration;
1220
import org.springframework.test.context.TestPropertySource;
13-
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
21+
import org.springframework.test.context.junit4.AbstractTransactionalJUnit4SpringContextTests;
22+
import org.springframework.test.context.transaction.AfterTransaction;
1423
import org.springframework.test.context.web.WebAppConfiguration;
1524
import org.springframework.test.web.servlet.MockMvc;
1625
import org.springframework.test.web.servlet.setup.MockMvcBuilders;
26+
import org.springframework.transaction.annotation.Propagation;
27+
import org.springframework.transaction.annotation.Transactional;
1728
import org.springframework.web.context.WebApplicationContext;
1829

19-
@RunWith(SpringJUnit4ClassRunner.class)
30+
@Transactional(propagation = Propagation.NOT_SUPPORTED)
2031
@ContextConfiguration(classes = { BaseTestConfig.class, AppTestConfig.class })
2132
@WebAppConfiguration
2233
@TestPropertySource("classpath:common.properties")
2334
@ActiveProfiles("test")
24-
public abstract class BaseWebContextSensitiveTest {
35+
public abstract class BaseWebContextSensitiveTest extends AbstractTransactionalJUnit4SpringContextTests {
2536

2637
@Autowired
2738
protected WebApplicationContext webApplicationContext;
2839

40+
@Autowired
41+
private DataSource dataSource;
42+
2943
protected MockMvc mockMvc;
3044

31-
protected void setUp() {
45+
private Map<String, IDataSet> originalStateCache;
46+
47+
private List<String[]> tablesToRestore;
48+
49+
protected BaseWebContextSensitiveTest() {
50+
this.originalStateCache = new HashMap<>();
51+
this.tablesToRestore = new ArrayList<>();
52+
}
53+
54+
protected BaseWebContextSensitiveTest(List<String[]> tablesToRestore) {
55+
this.originalStateCache = new HashMap<>();
56+
this.tablesToRestore = tablesToRestore != null ? tablesToRestore : new ArrayList<>();
57+
}
58+
59+
protected void setUp() throws Exception {
3260
mockMvc = MockMvcBuilders.webAppContextSetup(this.webApplicationContext).build();
3361
}
3462

@@ -44,4 +72,107 @@ public <T> T mapFromJson(String json, Class<T> clazz) throws IOException {
4472
objectMapper.enable(DeserializationFeature.ACCEPT_SINGLE_VALUE_AS_ARRAY);
4573
return objectMapper.readValue(json, clazz);
4674
}
75+
76+
/**
77+
* Executes a dataset with state management - preserves and restores the
78+
* original state of affected tables after execution.
79+
*/
80+
protected void executeDataSetWithStateManagement(String datasetFilename) throws Exception {
81+
if (datasetFilename == null) {
82+
throw new NullPointerException("Please provide test dataset file to execute!");
83+
}
84+
85+
IDatabaseConnection connection = null;
86+
try {
87+
connection = new DatabaseConnection(dataSource.getConnection());
88+
DatabaseConfig config = connection.getConfig();
89+
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
90+
91+
IDataSet newDataSet = loadDataSet(datasetFilename);
92+
String[] tableNames = newDataSet.getTableNames();
93+
94+
// Backup current state of affected tables
95+
IDataSet currentState = connection.createDataSet(tableNames);
96+
originalStateCache.put(Arrays.toString(tableNames), currentState);
97+
tablesToRestore.add(tableNames);
98+
99+
executeDataSet(datasetFilename);
100+
} finally {
101+
if (connection != null) {
102+
connection.close();
103+
}
104+
}
105+
}
106+
107+
/**
108+
* This method will be called after each transaction to restore the database
109+
* state
110+
*/
111+
@AfterTransaction
112+
@SuppressWarnings("unused")
113+
protected void restoreDatabase() throws Exception {
114+
try {
115+
for (String[] tableNames : tablesToRestore) {
116+
String key = Arrays.toString(tableNames);
117+
IDataSet originalState = originalStateCache.get(key);
118+
if (originalState != null) {
119+
IDatabaseConnection connection = null;
120+
try {
121+
connection = new DatabaseConnection(dataSource.getConnection());
122+
DatabaseConfig config = connection.getConfig();
123+
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
124+
125+
DatabaseOperation.CLEAN_INSERT.execute(connection, originalState);
126+
} finally {
127+
if (connection != null) {
128+
connection.close();
129+
}
130+
}
131+
originalStateCache.remove(key);
132+
}
133+
}
134+
} finally {
135+
originalStateCache.clear();
136+
tablesToRestore.clear();
137+
}
138+
}
139+
140+
/**
141+
* Loads a dataset from an XML file.
142+
*/
143+
private IDataSet loadDataSet(String datasetFilename) throws Exception {
144+
try (InputStream inputStream = getClass().getClassLoader().getResourceAsStream(datasetFilename)) {
145+
if (inputStream == null) {
146+
throw new IllegalArgumentException("Dataset file '" + datasetFilename + "' not found in classpath");
147+
}
148+
return new FlatXmlDataSet(inputStream);
149+
}
150+
}
151+
152+
/**
153+
* Executes a dataset from an XML file.
154+
*/
155+
protected void executeDataSet(String datasetFilename) throws Exception {
156+
if (datasetFilename == null) {
157+
throw new NullPointerException("please provide test dataset file to execute!");
158+
}
159+
160+
InputStream inputStream = getClass().getClassLoader().getResourceAsStream(datasetFilename);
161+
try (inputStream) {
162+
if (inputStream == null) {
163+
throw new IllegalArgumentException("Dataset file '" + datasetFilename + "' not found in classpath");
164+
}
165+
IDatabaseConnection connection = new DatabaseConnection(dataSource.getConnection());
166+
167+
DatabaseConfig config = connection.getConfig();
168+
config.setProperty(DatabaseConfig.FEATURE_ALLOW_EMPTY_FIELDS, true);
169+
IDataSet dataset = new FlatXmlDataSet(inputStream);
170+
171+
try {
172+
DatabaseOperation.REFRESH.execute(connection, dataset);
173+
} finally {
174+
connection.close();
175+
}
176+
}
177+
}
47178
}

src/test/java/org/openelisglobal/dictionary/rest/controller/DictionaryMenuRestControllerTest.java

Lines changed: 8 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,10 @@
2020
import org.openelisglobal.dictionarycategory.valueholder.DictionaryCategory;
2121
import org.springframework.beans.factory.annotation.Autowired;
2222
import org.springframework.http.MediaType;
23+
import org.springframework.test.annotation.Rollback;
2324
import org.springframework.test.web.servlet.MvcResult;
2425

26+
@Rollback
2527
public class DictionaryMenuRestControllerTest extends BaseWebContextSensitiveTest {
2628

2729
@Autowired
@@ -32,8 +34,9 @@ public class DictionaryMenuRestControllerTest extends BaseWebContextSensitiveTes
3234

3335
@Before
3436
@Override
35-
public void setUp() {
37+
public void setUp() throws Exception {
3638
super.setUp();
39+
executeDataSetWithStateManagement("testdata/dictionary.xml");
3740
}
3841

3942
@Test
@@ -47,9 +50,10 @@ public void getDictionaryMenuList_shouldReturnDictionaryMenu() throws Exception
4750
List<DictionaryMenuForm> menuList = Arrays.asList(super.mapFromJson(content, DictionaryMenuForm[].class));
4851
assertThat(menuList.get(0).getMenuList().get(0).getId(), is("1"));
4952
assertThat(menuList.get(0).getMenuList().get(0).getIsActive(), is("Y"));
50-
assertThat(menuList.get(0).getMenuList().get(0).getDictEntry(), is("INFLUENZA VIRUS A RNA DETECTED"));
51-
assertThat(menuList.get(0).getMenuList().get(0).getSortOrder(), is(100));
52-
assertThat(menuList.get(0).getMenuList().get(0).getDictionaryCategory().getCategoryName(), is("CG"));
53+
assertThat(menuList.get(0).getMenuList().get(0).getDictEntry(), is("Dictionary Entry 1"));
54+
assertThat(menuList.get(0).getMenuList().get(0).getSortOrder(), is(1));
55+
assertThat(menuList.get(0).getMenuList().get(0).getDictionaryCategory().getCategoryName(),
56+
is("Category Name 1"));
5357
}
5458

5559
@Test
@@ -64,26 +68,6 @@ public void fetchDictionaryCategories_shouldFetchDictionaryDescriptions() throws
6468
assertThat(menuList, notNullValue());
6569
}
6670

67-
// TODO: To be looked into later
68-
69-
// @Test
70-
// public void createDictionary_shouldSuccessfullyCreateDictionary() throws
71-
// Exception {
72-
// Dictionary dictionary = createDictionaryObject();
73-
// String toJson = super.mapToJson(dictionary);
74-
//
75-
// MvcResult mvcResult = super.mockMvc.perform(
76-
// post("/rest/dictionary")
77-
// .accept(MediaType.APPLICATION_JSON_VALUE)
78-
// .contentType(MediaType.APPLICATION_JSON_VALUE)
79-
// .content(toJson)).andReturn();
80-
//
81-
// int status = mvcResult.getResponse().getStatus();
82-
// assertEquals(201, status);
83-
// String content = mvcResult.getResponse().getContentAsString();
84-
// assertEquals(content, "Dictionary created successfully");
85-
// }
86-
8771
@Test
8872
public void showDeleteDictionary_shouldSuccessfullyDeleteDictionary() throws Exception {
8973
MvcResult getMenu = super.mockMvc.perform(get("/rest/DictionaryMenu").accept(MediaType.APPLICATION_JSON_VALUE)

0 commit comments

Comments
 (0)