-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathTutorial.html
793 lines (627 loc) · 31.1 KB
/
Tutorial.html
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
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
<!DOCTYPE html>
<!--
| Generated by Apache Maven Doxia Site Renderer 1.7.4 at 2021-09-25
| Rendered using Apache Maven Fluido Skin 1.5
-->
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="Date-Revision-yyyymmdd" content="20210925" />
<meta http-equiv="Content-Language" content="en" />
<title>JDBDT – Tutorial</title>
<link rel="stylesheet" href="./css/apache-maven-fluido-1.5.min.css" />
<link rel="stylesheet" href="./css/site.css" />
<link rel="stylesheet" href="./css/print.css" media="print" />
<script type="text/javascript" src="./js/apache-maven-fluido-1.5.min.js"></script>
</head>
<body class="topBarDisabled">
<div class="container-fluid">
<div id="banner">
<div class="pull-left">
<a href="./" id="bannerLeft">
<img src="images/jdbdt-logo.png" alt="JDBDT"/>
</a>
</div>
<div class="pull-right"> </div>
<div class="clear"><hr/></div>
</div>
<div id="breadcrumbs">
<ul class="breadcrumb">
<li id="publishDate">Last Published: 2021-09-25
<span class="divider">|</span>
</li>
<li id="projectVersion">Version: 1.4.1
</li>
</ul>
</div>
<div class="row-fluid">
<div id="leftColumn" class="span2">
<div class="well sidebar-nav">
<ul class="nav nav-list">
<li class="nav-header">JDBDT</li>
<li>
<a href="index.html" title="Home">
<span class="none"></span>
Home</a>
</li>
<li>
<a href="MIT_License.html" title="License">
<span class="none"></span>
License</a>
</li>
<li class="nav-header">Reference</li>
<li>
<a href="Facade.html" title="API facade">
<span class="none"></span>
API facade</a>
</li>
<li>
<a href="DB.html" title="Database handles">
<span class="none"></span>
Database handles</a>
</li>
<li>
<a href="DataSources.html" title="Data sources">
<span class="none"></span>
Data sources</a>
</li>
<li>
<a href="DataSets.html" title="Data sets">
<span class="none"></span>
Data sets</a>
</li>
<li>
<a href="DBSetup.html" title="Database setup">
<span class="none"></span>
Database setup</a>
</li>
<li>
<a href="DBAssertions.html" title="Assertions">
<span class="none"></span>
Assertions</a>
</li>
<li>
<a href="Logs.html" title="Logging format">
<span class="none"></span>
Logging format</a>
</li>
<li>
<a href="Compatibility.html" title="Compatibility">
<span class="none"></span>
Compatibility</a>
</li>
<li>
<a href="apidocs/index.html" title="Javadoc">
<span class="none"></span>
Javadoc</a>
</li>
<li class="nav-header">Tutorial</li>
<li class="active">
<a href="#"><span class="none"></span>Guide</a>
</li>
<li>
<a href="http://github.com/JDBDT/jdbdt-tutorial" class="externalLink" title="Code @ GitHub">
<span class="none"></span>
Code @ GitHub</a>
</li>
<li class="nav-header">Development</li>
<li>
<a href="http://search.maven.org/#search%7Cga%7C1%7Cjdbdt" class="externalLink" title="Maven Central">
<span class="none"></span>
Maven Central</a>
</li>
<li>
<a href="https://github.com/JDBDT/jdbdt/" class="externalLink" title="Source code">
<span class="none"></span>
Source code</a>
</li>
<li>
<a href="https://github.com/JDBDT/jdbdt/issues/" class="externalLink" title="Issue tracker">
<span class="none"></span>
Issue tracker</a>
</li>
<li>
<a href="https://travis-ci.org/JDBDT/jdbdt/" class="externalLink" title="Travis CI">
<span class="none"></span>
Travis CI</a>
</li>
<li>
<a href="https://ci.appveyor.com/project/edrdo/jdbdt" class="externalLink" title="AppVeyor CI">
<span class="none"></span>
AppVeyor CI</a>
</li>
<li>
<a href="https://sonarcloud.io/organizations/jdbdt/projects" class="externalLink" title="SonarCloud">
<span class="none"></span>
SonarCloud</a>
</li>
<li>
<a href="https://www.codefactor.io/repository/github/jdbdt/jdbdt" class="externalLink" title="CodeFactor">
<span class="none"></span>
CodeFactor</a>
</li>
<li>
<a href="project-info.html" title="Maven reports">
<span class="none"></span>
Maven reports</a>
</li>
<li>
<a href="Inception.html" title="Inception">
<span class="none"></span>
Inception</a>
</li>
</ul>
<hr />
<div id="poweredBy">
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<div class="clear"></div>
<a href="http://maven.apache.org/" title="Built by Maven" class="poweredBy">
<img class="builtBy" alt="Built by Maven" src="./images/logos/maven-feather.png" />
</a>
</div>
</div>
</div>
<div id="bodyColumn" class="span10" >
<h1>Tutorial</h1>
<p>This tutorial will help you understand the essential features of JDBDT.</p>
<p><a name="TheCode"></a></p>
<div class="section">
<h2><a name="Tutorial_code"></a>Tutorial code</h2>
<div class="section">
<h3><a name="GitHub_repository"></a>GitHub repository <a name="TheCode.GetIt"></a></h3>
<p>Get the tutorial code from <a class="externalLink" href="http://github.com/JDBDT/jdbdt-tutorial">GitHub</a>:</p>
<div class="source">
<div class="source"><pre class="prettyprint">git clone [email protected]:JDBDT/jdbdt-tutorial.git
</pre></div></div>
<p><a name="TheCode.MavenProject"></a></p></div>
<div class="section">
<h3><a name="Maven_project_overview"></a>Maven project overview</h3>
<p>The code is organized as a <a class="externalLink" href="http://maven.apache.org">Maven</a> project, and comprises the following artifacts:</p>
<ul>
<li>An SQL table creation script for a table called <tt>USERS</tt> (<tt>src/main/resources/tableCreation.sql</tt>).</li>
<li><tt>User</tt>, a POJO class to store user data (<tt>src/main/java/org/jdbdt/tutorial/User.java</tt>)</li>
<li><tt>UserDAO</tt>, a data-access object (DAO) class for user data (<tt>src/main/java/org/jdbdt/tutorial/UserDAO.java</tt>).</li>
<li><tt>UserDAOTest</tt>, a class containing <a class="externalLink" href="http://junit.org">JUnit</a> tests for <tt>UserDAO</tt>, making use of JDBDT (<tt>src/test/java/org/jdbdt/tutorial/UserDAOTest.java</tt>). This class will be our main point of interest.</li>
<li>Subclasses of <tt>UserDAOTest</tt>, that merely configure the database driver to use. There are three such classes <tt>DerbyTest</tt>, <tt>H2Test</tt>, <tt>HSQLDBTest</tt> (in <tt>src/test/java/org/jdbdt/tutorial</tt>). As their name indicates, they make use of JDBC drivers for <a class="externalLink" href="http://db.apache.org/derby">Apache Derby</a>, <a class="externalLink" href="http://h2database.com">H2</a>, and <a class="externalLink" href="http://hsqldb.org">HSQLDB</a>.</li>
<li>A JUnit test suite, <tt>AllTests</tt>, allowing tests in all classes mentioned above to be executed at once (<tt>src/test/java/org/jdbdt/tutorial/AllTests.java</tt>).</li>
</ul>
<p><a name="TheCode.RunningTheTests"></a></p></div>
<div class="section">
<h3><a name="Running_the_tests"></a>Running the tests</h3>
<p>In the command line go to the root folder of the project and type <tt>mvn test</tt> to execute the <tt>AllTests</tt> suite. </p>
<p>Otherwise, import the project using a Maven-compatible IDE and run the tests from the IDE environment. <a class="externalLink" href="http://eclipse.org">Eclipse</a> users will find that a <tt>.project</tt> file is already in the root folder.</p>
<p><a name="TheCode.TheTestSubject"></a></p></div>
<div class="section">
<h3><a name="The_test_subject"></a>The test subject</h3>
<p>The SUT of the tutorial is the <tt>UserDAO</tt> class. Objects of this kind works as a data-access object for a database table called <tt>USERS</tt>, whose Java representation is given by the POJO <tt>User</tt> class. These items are described below.</p>
<div class="section">
<h4><a name="The_USERS_table"></a>The <tt>USERS</tt> table</h4>
<p>The <tt>USERS</tt> table represents user data in the form of a numeric id (primary key), a unique login, a name, a password, a role, and a creation date. The code for table creation below should be self-explanatory. A sequence or identity column setting could be associated to the <tt>ID</tt> column, but we keep the example as simple as possible to ensure portability for different database engines. Likewise, for <tt>ROLE</tt>, a reference table or an <tt>ENUM</tt> type (as supported by some engines) could be used alternatively.</p>
<div class="source">
<div class="source"><pre class="prettyprint">CREATE TABLE USERS
(
ID INTEGER PRIMARY KEY NOT NULL ,
LOGIN VARCHAR(16) UNIQUE NOT NULL,
NAME VARCHAR(32),
PASSWORD VARCHAR(32) NOT NULL,
ROLE VARCHAR(7) DEFAULT 'REGULAR' NOT NULL
CHECK (ROLE IN ('ADMIN', 'REGULAR', 'GUEST')),
CREATED DATE NOT NULL
)
</pre></div></div></div>
<div class="section">
<h4><a name="The_User_class"></a>The <tt>User</tt> class</h4>
<p>The <tt>User</tt> class is a POJO class with getter and setter methods for each of the user attributes (e.g.,<tt>getId</tt> and <tt>setId</tt>). Additionally, it overrides a number of <tt>java.lang.Object</tt> methods for convenience of use in test code (e.g., <tt>equals</tt>). </p></div>
<div class="section">
<h4><a name="The_UserDAO_class"></a>The <tt>UserDAO</tt> class</h4>
<p>The <tt>UserDAO</tt> class defines methods for interfacing with the <tt>USERS</tt> table using <tt>User</tt> objects. The methods are in correspondence to database operations for user insertion, update, removal and retrieval.</p>
<ul>
<li><tt>insertUser(u)</tt>: inserts a new user.</li>
<li><tt>updateUser(u)</tt>: update an existing user.</li>
<li><tt>deleteUser(u)</tt>: delete a user.</li>
<li><tt>deleteAllUsers()</tt>: delete all users.</li>
<li><tt>getUser(id)</tt>: get user data by id.</li>
<li><tt>getUser(login)</tt>: get user data by login.</li>
<li><tt>getAllUsers()</tt>: get a list of all users.</li>
<li><tt>getUsers(r)</tt>: get a list of all users with a given role.</li>
</ul>
<p><a name="TheTestCode"></a></p></div></div></div>
<div class="section">
<h2><a name="Test_code__use_of_JDBDT"></a>Test code / use of JDBDT</h2>
<p><a name="TheTestCode.Imports"></a></p>
<div class="section">
<h3><a name="JDBDT_import_statements"></a>JDBDT import statements</h3>
<p>The test code of <tt>UserDAOTest</tt> makes use of JDBDT to setup and validate the contents of the database. You should notice the following JDBDT imports:</p>
<div class="source">
<div class="source"><pre class="prettyprint">import static org.jdbdt.JDBDT.*;
import org.jdbdt.Conversion;
import org.jdbdt.DB;
import org.jdbdt.DataSet;
import org.jdbdt.Table;
</pre></div></div>
<p>The static import (the very first one) relates to methods in the <a href="Facade.html">JDBDT facade</a> that exposes the core JDBDT API.</p>
<p><a name="TheTestCode.SetupAndTeardown"></a></p></div>
<div class="section">
<h3><a name="Database_setup_and_tear-down"></a>Database setup and tear-down</h3>
<div class="section">
<h4><a name="Initial_setup"></a>Initial setup</h4>
<p>To setup the database connection and define the initial contents of the database, each subclass of <tt>UserDAOTest</tt> defines a <tt>globalSetup</tt> method that is executed once before all tests, since it is marked with the <tt>@BeforeClass</tt> JUnit annotation; the method calls <tt>UserDAO.globalSetup(dbDriverClass,dbURL)</tt> in the parent class, parameterizing the JDBC driver class to load and the database URL to use for the actual setup. For instance, <tt>DerbyTest</tt> contains:</p>
<div class="source">
<div class="source"><pre class="prettyprint">private static final String
JDBC_DRIVER_CLASS = "org.apache.derby.jdbc.EmbeddedDriver";
private static final String
DATABASE_URL = "jdbc:derby:./db/derby/jdbdtTutorial;create=true";
@BeforeClass
public static void globalSetup() throws Throwable {
globalSetup(JDBC_DRIVER_CLASS, DATABASE_URL);
}
</pre></div></div>
<p>This layout is merely a convenient one for the purpose of testing multiple JDBC drivers in the tutorial code. In the core code at <tt>UserDAOTest</tt> we have:</p>
<div class="source">
<div class="source"><pre class="prettyprint">protected static
void globalSetup(String jdbcDriverClass, String databaseURL) ... {
...
}
</pre></div></div>
<p>that proceeds in the following steps:</p>
<ul>
<li>
<p>We first ensure that the JDBC driver class is loaded.</p>
<div class="source">
<div class="source"><pre class="prettyprint">// Load JDBC driver class
Class.forName(jdbcDriverClass);
</pre></div></div></li>
<li>
<p>The JDBDT <a href="DB.html">database handle</a> is then created.</p>
<div class="source">
<div class="source"><pre class="prettyprint">// Create database handle
theDB = database(databaseURL);
</pre></div></div></li>
<li>
<p>So is the <tt>UserDAO</tt> instance, our SUT, along with the <tt>USERS</tt> table (JDBDT provides no facilities to create the table itself) …</p>
<div class="source">
<div class="source"><pre class="prettyprint">// Create DAO and in turn let it create USERS table
theDAO = new UserDAO(theDB.getConnection());
theDAO.createTable();
</pre></div></div></li>
<li>
<p>… and a JDBDT <tt>Table</tt> <a href="DataSources.html">data source</a> for the <tt>USERS</tt> table. </p>
<div class="source">
<div class="source"><pre class="prettyprint">// Create table data source.
theTable = table("USERS")
.columns("ID",
"LOGIN",
"NAME",
"PASSWORD",
"ROLE",
"CREATED" )
.build(theDB);
</pre></div></div></li>
<li>
<p>… plus, finally, the <a href="DataSets.html">data set</a> for the initial contents of the database. The strategy in this case is to use a <a href="DataSets.html#Creation.Builder">data set builder</a>. We populate the database with 1 <tt>ADMIN</tt> user, 3 <tt>REGULAR</tt> users, and 2 <tt>GUEST</tt> users. The data set builder methods allow a succinct definition of the data, as follows:</p>
<div class="source">
<div class="source"><pre class="prettyprint">// Define data set for populating the database
theInitialData
= builder(theTable)
.sequence("ID", 0)
.value("LOGIN", "root")
.sequence("PASSWORD", i -> "pass" + i)
.nullValue("NAME")
.value("CREATED", FIXED_DATE)
.value("ROLE", ADMIN)
.generate(1)
.sequence("LOGIN", "alice", "bob", "charles")
.sequence("NAME", "Alice", "Bob", "Charles")
.value("ROLE", REGULAR)
.generate(3)
.sequence("LOGIN", i -> "guest" + i, 1)
.sequence("NAME", i -> "Guest User " + i, 1)
.value("ROLE", GUEST)
.generate(2)
.data();
// dump(theInitialData, System.err);
</pre></div></div></li>
</ul>
<p>Uncomment the last statement above, the call to <tt>dump</tt>, if you wish to see some <a href="Logs.html">debug output</a> sent to <tt>System.err</tt> listing the data set. The following table summarizes the created entries (note that <tt>FIXED_DATE</tt> equals <tt>2016-01-01</tt>):</p>
<table class="table table-striped" border="1">
<tr class="a">
<th align="left">
<tt>ID</tt>
</th>
<th align="left">
<tt>LOGIN</tt>
</th>
<th align="left">
<tt>NAME</tt>
</th>
<th align="left">
<tt>PASSWORD</tt>
</th>
<th align="left">
<tt>ROLE</tt>
</th>
<th align="left">
<tt>CREATED</tt>
</th>
</tr>
<tr class="b">
<td align="left">
<tt>0</tt>
</td>
<td align="left">
<tt>root</tt>
</td>
<td align="left">
<tt>NULL</tt>
</td>
<td align="left">
<tt>pass0</tt>
</td>
<td align="left">
<tt>ADMIN</tt>
</td>
<td align="left">
<tt>2016-01-01</tt>
</td>
</tr>
<tr class="a">
<td align="left">
<tt>1</tt>
</td>
<td align="left">
<tt>alice</tt>
</td>
<td align="left">
<tt>Alice</tt>
</td>
<td align="left">
<tt>pass1</tt>
</td>
<td align="left">
<tt>REGULAR</tt>
</td>
<td align="left">
<tt>2016-01-01</tt>
</td>
</tr>
<tr class="b">
<td align="left">
<tt>2</tt>
</td>
<td align="left">
<tt>bob</tt>
</td>
<td align="left">
<tt>Bob</tt>
</td>
<td align="left">
<tt>pass2</tt>
</td>
<td align="left">
<tt>REGULAR</tt>
</td>
<td align="left">
<tt>2016-01-01</tt>
</td>
</tr>
<tr class="a">
<td align="left">
<tt>3</tt>
</td>
<td align="left">
<tt>charles</tt>
</td>
<td align="left">
<tt>Charles</tt>
</td>
<td align="left">
<tt>pass3</tt>
</td>
<td align="left">
<tt>REGULAR</tt>
</td>
<td align="left">
<tt>2016-01-01</tt>
</td>
</tr>
<tr class="b">
<td align="left">
<tt>4</tt>
</td>
<td align="left">
<tt>guest1</tt>
</td>
<td align="left">
<tt>Guest User 1</tt>
</td>
<td align="left">
<tt>pass4</tt>
</td>
<td align="left">
<tt>GUEST</tt>
</td>
<td align="left">
<tt>2016-01-01</tt>
</td>
</tr>
<tr class="a">
<td align="left">
<tt>5</tt>
</td>
<td align="left">
<tt>guest2</tt>
</td>
<td align="left">
<tt>Guest User 2</tt>
</td>
<td align="left">
<tt>pass5</tt>
</td>
<td align="left">
<tt>GUEST</tt>
</td>
<td align="left">
<tt>2016-01-01</tt>
</td>
</tr>
</table>
<ul>
<li>
<p>The data set of the previous step, <tt>theInitialData</tt>, is used to <a href="DBSetup.html#Insert">populate</a> the database table.</p>
<div class="source">
<div class="source"><pre class="prettyprint">// Populate database using the built data set
populate(theInitialData);
</pre></div></div></li>
<li>
<p>The final step disables auto-commit for the JDBC connection, a prerequisite for using JDBDT save-points, that are discussed <a href="Tutorial.html#TheTestCode.PerTestSetupAndTeardown">later</a> in this tutorial. </p>
<div class="source">
<div class="source"><pre class="prettyprint">// Set auto-commit off (to allow for save-points)
theDB.getConnection().setAutoCommit(false);
</pre></div></div></li>
</ul></div>
<div class="section">
<h4><a name="Test_teardown"></a>Test teardown</h4>
<p>The <tt>globalTeardown</tt> method of <tt>UserDAOTest</tt>, annotated with JUnit’s <tt>@AfterClass</tt> annotation, is executed after all tests are done. Its purpose is to leave the test database in a clean state and freeing up any resources.</p>
<div class="source">
<div class="source"><pre class="prettyprint">@AfterClass
public static void globalTeardown() {
truncate(theTable);
teardown(theDB, true);
}
</pre></div></div>
<p>The <tt>truncate(theTable)</tt> statement <a href="DBSetup.html#Clean">truncates</a> the <tt>USERS</tt> table. Then <tt>teardown(theDB, true)</tt> frees up any internal resources used by the <a href="DB.html">database handle</a> and closes the underlying database connection.</p></div>
<div class="section">
<h4><a name="Per-test_setup_and_tear-down"></a>Per-test setup and tear-down</h4>
<p>In <tt>UserDAOTest</tt>, the <tt>saveState</tt> and <tt>restoreState</tt> methods are executed respectively before and after each test, in line with the <tt>@Before</tt> and <tt>@After</tt> JUnit annotations in each method below. Their purpose is to make sure each test starts with the same initial database state (<a href="Tutorial.html#TheTestCode.SetupAndTeardown.Initial">described earlier</a>), making use of <a href="DBSetup.html#SaveAndRestore">JDBDT save-points</a>.</p>
<div class="source">
<div class="source"><pre class="prettyprint">@Before
public void saveState() {
// Set save point
save(theDB);
}
@After
public void restoreState() {
// Restore state to save point
restore(theDB);
}
</pre></div></div>
<p>The <tt>save(theDB)</tt> call creates a database save-point, beginning a new database transaction. In symmetry, the <tt>restore(theDB)</tt> call rolls back any database changes made by the current transaction to the JDBDT save-point. Note also that, for portability reasons, only one save-point is maintained per database handle and that there must be exactly one call to <tt>restore</tt> per each call to <tt>save</tt>.</p>
<p>This setup relies on disabling auto-commit for the database in <tt>globalSetup</tt> as <a href="Tutorial.html#TheTestCode.DBSetup">described before</a>, and also that <tt>UserDAO</tt> does not issue a database commit (that would make any changes permanent and terminate the transaction started with <tt>save(theDB)</tt>). </p>
<p><a name="TheTestCode.DBValidation"></a></p></div></div>
<div class="section">
<h3><a name="Tests_and_assertions"></a>Tests and assertions</h3>
<p>The tests in <tt>UserDAOTest</tt>, marked with the JUnit <tt>@Test</tt> annotation, validate the different methods in <tt>UserDAO</tt>, using <a href="DBAssertions.html">JDBDT assertions</a>. These take form as <a href="DBAssertions.html#DeltaAssertions">delta assertions</a>, <a href="DBAssertions.html#StateAssertions">state assertions</a>, or <a href="DBAssertions.html#DataSetAssertions">plain data set assertions</a>.</p>
<p>Before discussing test methods and assertions, we first make note of an auxiliary method in <tt>UserDAOTest</tt> called <tt>toDataSet</tt>, that is used throughout the rest of the code. It provides a shorthand to create <a href="DataSets.html#Creation.Typed">a (typed) data set</a> from a single <tt>User</tt> instance. The conversion from <tt>User</tt> instances to row format is defined by the <tt>CONVERSION</tt> function (defined as a lambda expression):</p>
<div class="source">
<div class="source"><pre class="prettyprint">private static final Conversion<User> CONVERSION =
u -> new Object[] {
u.getId(),
u.getLogin(),
u.getName(),
u.getPassword(),
u.getRole().toString(),
u.getCreated()
};
static DataSet toDataSet(User u) {
return data(theTable, CONVERSION).row(u);
}
</pre></div></div>
<div class="section">
<h4><a name="Delta_assertions"></a>Delta assertions <a name="TheTestCode.DBValidation.DeltaAssertions"></a></h4>
<p>As an example of a <a href="DBAssertions.html#DeltaAssertions">delta assertion</a>, consider <tt>testNonExistingUserInsertion</tt>:</p>
<div class="source">
<div class="source"><pre class="prettyprint">@Test
public void testNonExistingUserInsertion() throws SQLException {
User u = nonExistingUser();
theDAO.insertUser(u);
assertInserted("DB change", toDataSet(u));
}
</pre></div></div>
<p>The code tests whether a new user is correctly inserted in the database via <tt>UserDAO.insertUser</tt>. It proceeds by first calling <tt>nonExistingUser()</tt>, an auxiliary method to creates a <tt>User</tt> instance that does not correspond to any entry in the <tt>USERS</tt> table. Then it calls <tt>theDAO.insertUser(u)</tt> to insert the user. To validate the database change <tt>assertInserted</tt>, a <a href="DBAssertions.html#DeltaAssertion">delta assertion</a> method, is used. The assertion specifies that the expected state should differ only by the addition of the new user, i.e., <tt>toDataSet(u)</tt>. A fresh database query is issued for the <tt>USERS</tt> table, and the delta is verified against the <a href="DBAssertions.html#Snapshots">database snapshot</a> defined in the <a href="Tutorial.html#TheTestCode.DBSetup">initial setup</a> of <tt>globalSetup</tt>, more precisely the <tt>populate(theInitialData)</tt> step in that method. </p></div>
<div class="section">
<h4><a name="State_assertions"></a>State assertions</h4>
<p>Now consider <tt>testNonExistingUserInsertionVariant</tt>, an alternative test method with the same purpose as <tt>testNonExistingUserInsertion</tt>, but that uses a <a href="DBAssertions.html#StateAssertions">state assertion</a> instead of a delta assertion:</p>
<div class="source">
<div class="source"><pre class="prettyprint">@Test
public void testNonExistingUserInsertionVariant() throws SQLException {
User u = nonExistingUser();
theDAO.insertUser(u);
DataSet expected = DataSet.join(theInitialData, toDataSet(u));
assertState("DB state", expected);
</pre></div></div>
<p>}</p>
<p>The assertion method is <tt>assertState</tt>, that takes the data set that is expected to match the current database state. The expected data set is formed by <tt>theInitialData</tt>, the data set defined in <tt>globalSetup</tt>, joined with <tt>toDataSet(u)</tt>.</p></div>
<div class="section">
<h4><a name="Plain_data_set_assertions"></a>Plain data set assertions</h4>
<p><a href="DBAssertions.html#DataSetAssertions">Plain data set assertions</a> match the contents of two data set instances, via the <tt>assertEquals</tt> method (this should not be confused with the JUnit assertion method variants with the same name).<br />For instance, the method is used in <tt>testGetAllUsers</tt>:</p>
<div class="source">
<div class="source"><pre class="prettyprint">@Test
public void testGetAllUsers() throws SQLException {
List<User> list = theDAO.getAllUsers();
DataSet expected = theInitialData;
DataSet actual = data(theTable, CONVERSION).rows(list);
assertEquals("User list", expected, actual);
assertUnchanged("No DB changes", theTable);
}
</pre></div></div>
<p><i>Note</i>: in addition to verifying the result of <tt>getAllUsers</tt> through <tt>assertEquals</tt>, the test code above also validates that <tt>getAllUsers</tt> did not change the <tt>USERS</tt> table through the call to <tt>assertUnchanged</tt> (a delta assertion method). This assertion provides an extra guarantee on the functionality of <tt>getAllUsers</tt>. </p></div>
<div class="section">
<h4><a name="Inspecting_assertion_errors"></a>Inspecting assertion errors</h4>
<p>When an assertion fails, <tt>DBAssertionError</tt> is thrown by JDBDT. Additionally, error information may be <a href="DB.html#Logging">logged</a> to a file or output stream in <a href="Logs.html">an XML format</a>. By default, assertion errors will be logged to <tt>System.err</tt>. Consider for instance <tt>testExistingUserDelete</tt> in <tt>UserDAOTest</tt>: </p>
<div class="source">
<div class="source"><pre class="prettyprint">@Test
public void testExistingUserDelete() throws SQLException {
User u = anExistingUser(); // -> change to nonExistingUser()
boolean deleted = theDAO.deleteUser(u);
assertDeleted("DB change", toDataSet(u));
assertTrue("return value", deleted);
}
</pre></div></div>
<p>If you change <tt>anExistingUser()</tt> above to <tt>nonExistingUser()</tt>, then <tt>assertDeleted</tt>, two lines below, will throw <tt>DBAssertionError</tt>. The user instance returned by <tt>nonExistingUser()</tt> does not exist in the database, hence <tt>theDAO.deleteUser(u)</tt> will fail to delete the equivalent entry in the <tt>USERS</tt> table.</p>
<p>In conjunction with <tt>DBAssertionError</tt>, the log message below will appear in <tt>System.err</tt>, where <tt>99</tt> / <tt>john99</tt> refers to the non-existing user. The assertion error is explained by the <tt>jdbdt-log-message/delta-assertion/errors/old-data</tt> section, indicating that the (non-existing) user entry was expected to be deleted but was actually not. For more details on the logging format, refer to <a href="Logs.html">this page</a>.</p>
<div class="source">
<div class="source"><pre class="prettyprint"><jdbdt-log-message ...>
...
<delta-assertion>
...
<errors>
<old-data>
<expected count="1">
<row>
<column java-type="java.lang.Integer" label="ID">99</column>
<column java-type="java.lang.String" label="LOGIN">john99</column>
<column java-type="java.lang.String" label="NAME">John Doe 99</column>
<column java-type="java.lang.String" label="PASSWORD">doeit 99</column>
<column java-type="java.lang.String" label="ROLE">REGULAR</column>
<column java-type="java.sql.Date" label="CREATED">2016-01-01</column>
</row>
</expected>
<actual count="0"/>
</old-data>
<new-data>
<expected count="0"/>
<actual count="0"/>
</new-data>
</errors>
</delta-assertion>
</jdbdt-log-message>
</pre></div></div></div></div></div>
</div>
</div>
</div>
<hr/>
<footer>
<div class="container-fluid">
<div class="row-fluid">
<p >Copyright © 2016–2021
<a href="http://jdbdt.org">JDBDT</a>.
All rights reserved.
</p>
</div>
</div>
</footer>
</body>
</html>