Hogan is the utility library which allows you to access DB intuitively.
As you know, DB processing needs boilerplate code.
Hogan expresses data structure with Spock like DSL (known as "data table DSL").
That's why you can access DB intuitively.
- Insert multiple tables
- Assert multiple tables (@Beta)
At first, please add following dependency and repository.
dependencies {
testCompile "io.disc99:hogan:0.9.2"
}
repositories {
jcenter()
}
There are two ways to enable Hogan DSL.
One way is to create subclass of Specification
.
The other way is to add @EnableHogan
annotation to the target class.
Create Database
class which processes DB access.
Constractor of Database
is a deregater to create groovy.sql.Sql
(new Sql or Sql.newInstance).
If you need more information, check the following link.
groovy.sql.Sql
Database db = new Database("jdbc:h2:mem:", "org.h2.Driver")
Describe table name whith label, and execute SQL each of it.
Execute 'Insert' according to the table definition.
And of cource you can deal with the number of labels.
class HoganSpec extends Specification {
def test() {
setup:
db.insert {
item_master:
id | name | price
1 | 'Apple' | 500
2 | 'Orange' | 250
sales:
id | day | item_id | num
1 | '2015-04-01' | 1 | 3
2 | '2015-04-02' | 2 | 1
3 | '2015-04-02' | 1 | 2
}
expect:
// ...
}
}
Followings are acutual executed SQL.
INSERT INTO ITEM_MASTER (ID, NAME, PRICE) VALUES (1, 'Apple', 500)
INSERT INTO ITEM_MASTER (ID, NAME, PRICE) VALUES (2, 'Orange', 250)
INSERT INTO SALES (ID, DAY, ITEM_ID, NUM) VALUES (1, '2015-04-01', 1, 3)
INSERT INTO SALES (ID, DAY, ITEM_ID, NUM) VALUES (2, '2015-04-02', 2, 1)
INSERT INTO SALES (ID, DAY, ITEM_ID, NUM) VALUES (3, '2015-04-02', 1, 2)
Assert to the table according to the definition.
And undefined columns will be ignored.
class HoganSpec extends Specification {
def test() {
when:
// ...
then:
db.assert {
item_master:
id | name
100 | 'Banana'
101 | 'Pine'
}
}
}
You will get following message when there's any discard.
assert actual == expected
| | |
| | [[ID:100, NAME:Banana], [ID:101, NAME:Pine]]
| false
[[ID:100, NAME:Banana], [ID:101, NAME:Pineapple]]