forked from eeichinger/jdbc-service-virtualisation
-
Notifications
You must be signed in to change notification settings - Fork 0
/
UseWireMockToMockJdbcResultSetsTest.java
378 lines (332 loc) · 15.2 KB
/
UseWireMockToMockJdbcResultSetsTest.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
package example;
import java.sql.PreparedStatement;
import java.util.ArrayList;
import java.util.List;
import javax.sql.DataSource;
import com.github.tomakehurst.wiremock.client.WireMock;
import com.github.tomakehurst.wiremock.junit.WireMockRule;
import lombok.Value;
import org.eeichinger.servicevirtualisation.jdbc.JdbcServiceVirtualizationFactory;
import org.junit.Before;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.ExpectedException;
import org.springframework.jdbc.BadSqlGrammarException;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import static org.hamcrest.MatcherAssert.*;
import static org.hamcrest.Matchers.*;
/**
* Demonstrates you to use the technique to just spy on a real database and intercept/mock only selected jdbc queries
* <p>
* Under the hood it uses P6Spy to spy on the jdbc connection and hooks into {@link PreparedStatement#executeQuery()}
* to redirect the call to WireMock.
* <p>
* If WireMock returns 404 (i.e. no match was found), an {@link AssertionError} is thrown.
*/
public class UseWireMockToMockJdbcResultSetsTest {
@Rule
public WireMockRule wireMockRule = new WireMockRule(0);
@Rule
public ExpectedException thrown = ExpectedException.none();
JdbcTemplate jdbcTemplate;
@Before
public void before() {
JdbcServiceVirtualizationFactory myP6MockFactory = new JdbcServiceVirtualizationFactory();
myP6MockFactory.setTargetUrl("http://localhost:" + wireMockRule.port() + "/sqlstub");
DataSource dataSource = myP6MockFactory.createMockDataSource();
jdbcTemplate = new JdbcTemplate(dataSource);
}
@Test
public void default_to_utf8_response_parsing() {
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
.withRequestBody(WireMock.equalTo("SELECT * FROM PEOPLE WHERE name=?"))
.willReturn(WireMock
.aResponse()
.withBody(""
+ "<resultset>"
+ " <row><name>Matthias Bernlöhr</name></row>"
+ "</resultset>"
)
)
);
String result = jdbcTemplate
.queryForObject(
"SELECT * FROM PEOPLE WHERE name=?"
, String.class
, args("Erich Eichinger")
);
assertThat(result, equalTo("Matthias Bernlöhr"));
}
@Test
public void can_mock_nullvalues() {
// setup mock resultsets
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("SELECT * FROM PEOPLE WHERE name=?"))
// return a recordset
.willReturn(WireMock
.aResponse()
.withHeader("content-type", "application/xml; charset=utf-8")
.withBody(""
+ "<resultset xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>"
+ "<cols><col>name</col><col>birthday</col><col>placeofbirth</col></cols>"
// you can mock NULL with named values by omitting the element or using xsi:nil='true' attribute
+ " <row><name>Erich Eichinger</name><placeofbirth xsi:nil='true' /></row>"
// you MUST use xsi:nil='true' for positional values
+ " <row><col>Matthias Bernlöhr</col><col xsi:nil='true' /><col xsi:nil='true'></col></row>"
+ "</resultset>"
)
)
);
RowMapper<Person> rowMapper = (rs, rowNum) -> {
return new Person(
rs.getString("name")
, rs.getString("birthday")
, rs.getString("placeofbirth")
);
};
List<Person> result = jdbcTemplate
.query(
"SELECT * FROM PEOPLE WHERE name=?"
, rowMapper
, args("Erich Eichinger")
);
Person erich = result.get(0);
assertThat(erich.getName(), equalTo("Erich Eichinger"));
assertThat(erich.getBirthdate(), nullValue());
assertThat(erich.getPlaceOfBirth(), nullValue());
Person matthias = result.get(1);
assertThat(matthias.getName(), equalTo("Matthias Bernlöhr"));
assertThat(matthias.getBirthdate(), nullValue());
assertThat(matthias.getPlaceOfBirth(), nullValue());
}
@Test
public void intercepts_matching_query_and_responds_with_mockresultset() {
final String NAME_ERICH_EICHINGER = "Erich Eichinger";
// setup mock resultsets
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("SELECT birthday FROM PEOPLE WHERE name = ?"))
// Parameters are sent with index has headername and value as headervalue
.withHeader("1", WireMock.equalTo(NAME_ERICH_EICHINGER))
// return a recordset
.willReturn(WireMock
.aResponse()
.withBody(""
+ "<resultset>"
+ " <cols><col>birthday</col></cols>"
+ " <row><val>1980-01-01</val></row>"
+ "</resultset>"
)
)
)
;
String dateTime = jdbcTemplate
.queryForObject(
"SELECT birthday FROM PEOPLE WHERE name = ?"
, String.class
, NAME_ERICH_EICHINGER
);
assertThat(dateTime, equalTo("1980-01-01"));
}
@Test
public void intercepts_matching_update_and_responds_with_int() {
final String NAME_ERICH_EICHINGER = "Erich Eichinger";
// setup mock resultsets
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("UPDATE PEOPLE set birthday=? WHERE name=?"))
// Parameters are sent with index has headername and value as headervalue
.withHeader("1", WireMock.equalTo("1970-01-01"))
.withHeader("2", WireMock.equalTo(NAME_ERICH_EICHINGER))
// return the number of rows affected
.willReturn(WireMock
.aResponse()
.withStatus(200)
.withBody("2")
)
)
;
int res = jdbcTemplate.update(
"UPDATE PEOPLE set birthday=? WHERE name=?", "1970-01-01", NAME_ERICH_EICHINGER
);
assertThat(res, equalTo(2));
}
@Test
public void intercepts_matching_query_and_responds_with_multi_column_mockresultset() {
final String NAME_ERICH_EICHINGER = "Erich Eichinger";
final String PLACE_OF_BIRTH = "Vienna";
// setup mock resultsets
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("SELECT birthday, placeofbirth FROM PEOPLE WHERE name = ?"))
// Parameters are sent with index has headername and value as headervalue
.withHeader("1", WireMock.equalTo(NAME_ERICH_EICHINGER))
// return a recordset
.willReturn(WireMock
.aResponse()
.withBody(""
+ "<resultset>"
+ " <cols><col>birthday</col><col>placeofbirth</col></cols>"
+ " <row>"
+ " <birthday>1980-01-01</birthday>"
+ " <placeofbirth>" + PLACE_OF_BIRTH + "</placeofbirth>"
+ " </row>"
+ "</resultset>"
)
)
)
;
String[] result = jdbcTemplate.queryForObject(
"SELECT birthday, placeofbirth FROM PEOPLE WHERE name = ?"
, new Object[]{NAME_ERICH_EICHINGER}
, (rs, rowNum) -> {
return new String[]{rs.getString(1), rs.getString(2)};
}
);
assertThat(result[0], equalTo("1980-01-01"));
assertThat(result[1], equalTo(PLACE_OF_BIRTH));
}
@Test
public void intercepts_matching_batch_update_and_responds_with_two_dimensional_int_array() {
// setup mock for batch 1 - always the last parameters of each batch will be sent
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("INSERT INTO PEOPLE (name, birthday, placeofbirth) " +
"VALUES (?, ?, ?)"))
// Parameters are sent with index has headername and value as headervalue
.withHeader("1", WireMock.matching("Matthias Bernlöhr")) // last arg of batch 1
.withHeader("2", WireMock.matching(".+"))
.withHeader("3", WireMock.matching(".+"))
// return a recordset
.willReturn(WireMock
.aResponse()
.withBody(""
+ "0,1"
)
)
);
// setup mock for batch 2 - always the last parameters of each batch will be sent
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("INSERT INTO PEOPLE (name, birthday, placeofbirth) " +
"VALUES (?, ?, ?)"))
// Parameters are sent with index has headername and value as headervalue
.withHeader("1", WireMock.matching("Volker Waltner")) // last arg of batch 2
.withHeader("2", WireMock.matching(".+"))
.withHeader("3", WireMock.matching(".+"))
// return a recordset
.willReturn(WireMock
.aResponse()
.withBody(""
+ "-1,-2"
)
)
);
List<Person> persons = new ArrayList<Person>() {{
add(new Person("Erich Erichinger", "1980-01-01", "Vienna"));
add(new Person("Matthias Bernlöhr", "1990-01-01", "Germany"));
add(new Person("Steffen Wegner", "1990-01-01", "Germany"));
add(new Person("Volker Waltner", "1980-01-01", "Germany"));
}};
int[][] result = jdbcTemplate.batchUpdate("INSERT INTO PEOPLE (name, birthday, placeofbirth) " +
"VALUES (?, ?, ?)", persons, 2, (ps, argument) -> {
ps.setString(1, argument.getName());
ps.setString(2, argument.getBirthdate());
ps.setString(3, argument.getPlaceOfBirth());
});
assertThat(result.length, equalTo(2));
assertThat(result[0][0], equalTo(0));
assertThat(result[0][1], equalTo(1));
assertThat(result[1][0], equalTo(-1));
assertThat(result[1][1], equalTo(-2));
}
@Test
public void intercepts_matching_batch_update_and_responds_with_int_array() {
// setup mock resultsets - always the last parameters of each batch will be sent
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("INSERT INTO PEOPLE (name, birthday, placeofbirth) " +
"VALUES (?, ?, ?)"))
// Parameters are sent with index has headername and value as headervalue
.withHeader("1", WireMock.matching("Volker Waltner")) // last arg of batch
.withHeader("2", WireMock.matching(".+"))
.withHeader("3", WireMock.matching(".+"))
// return a recordset
.willReturn(WireMock
.aResponse()
.withBody(""
+ "0,1,-1,-2"
)
)
);
List<Object[]> batchArgs = new ArrayList<Object[]>() {{
add(new Object[]{"Erich Erichinger", "1980-01-01", "Vienna"});
add(new Object[]{"Matthias Bernlöhr", "1990-01-01", "Germany"});
add(new Object[]{"Steffen Wegner", "1990-01-01", "Germany"});
add(new Object[]{"Volker Waltner", "1980-01-01", "Germany"});
}};
int[] result = jdbcTemplate.batchUpdate("INSERT INTO PEOPLE (name, birthday, placeofbirth) " +
"VALUES (?, ?, ?)", batchArgs);
assertThat(result.length, equalTo(4));
assertThat(result[0], equalTo(0));
assertThat(result[1], equalTo(1));
assertThat(result[2], equalTo(-1));
assertThat(result[3], equalTo(-2));
}
@Test
public void emulate_sqlexception_by_returning_400() {
thrown.expect(BadSqlGrammarException.class);
final String NAME = "Hugo Simon";
// setup mock resultsets
WireMock.stubFor(WireMock
.post(WireMock.urlPathEqualTo("/sqlstub"))
// SQL Statement is posted in the body, use any available matchers to match
.withRequestBody(WireMock.equalTo("SYNTAX ERROR"))
// return a recordset
.willReturn(WireMock
.aResponse()
.withStatus(400)
.withHeader("reason", "unexpected token: SYNTAX")
.withHeader("SQLState", "42581")
.withHeader("vendorCode", "1234")
)
)
;
String dateTime = jdbcTemplate
.queryForObject(
"SYNTAX ERROR"
, String.class
, NAME
);
}
@Test
public void passthrough_nonmatching_queries_throws_assertionerror() {
thrown.expect(AssertionError.class);
final String NAME = "Hugo Simon";
String dateTime = jdbcTemplate
.queryForObject(
"SELECT birthday FROM PEOPLE WHERE name = ?"
, String.class
, NAME
);
}
@Value
private static class Person {
String name;
String birthdate;
String placeOfBirth;
}
private static Object[] args(Object... args) {
return args;
}
}