从Groovy中的表格数据填充域对象 [英] Populate domain objects from tabular data in groovy
问题描述
已经相当多地使用了Spock,并且非常喜欢在测试中将表用于输入/输出方案的能力。
Have been using Spock a fair bit, and really like the ability to use tables in tests for input/output scenarios.
spock文档中的示例:
example from spock docs:
class Math extends Specification {
def "maximum of two numbers"(int a, int b, int c) {
expect:
Math.max(a, b) == c
where:
a | b | c
1 | 3 | 3
7 | 4 | 4
0 | 0 | 0
}
}
我在金融行业工作,许多交易书籍。
I work in the finance industry where we deal with a lot of trading "books".
以表格形式表示这些书籍将非常有用。
Would be great to represent those books in tabular form.
而不是使用构建器,例如:
So instead of using builders, e.g:
builder.addQuote( 1000000, 1.1220, 1.2230)
.addQuote( 2000000, 1.1219, 1.2233)
.addQuote(10000000, 1.1217, 1.2234)
.addQuote(15000000, 1.1216, 1.2240)
使用某种类型的表会很棒:
Would be great to use some kind of table:
List<Quote> quotes = new ArrayList<Quote>();
MyUtil.insertInto(quotes).fromTable{
quantity | bid | ask
1000000 | 1.1220 | 1.2230
2000000 | 1.1219 | 1.2233
10000000 | 1.1217 | 1.2234
15000000 | 1.1216 | 1.2240
}
已经看到某人以某种方式做到了这一点此处,但是该示例将结果分配给了行对象。
Have seen someone go some of the way to do this here, but the example assigns the results to a general "Row" object.
最好有一个实用程序,它使用第一行的字段名将行值写入给定的域对象。
Would be great to have a utility which writes the row values to a given domain object, using the field names from the first row.
推荐答案
我写了一个API来解决我自己的问题。
I've written an API which addresses my own question.
称为GroovyTables。位于: https://github.com/tools4j/groovy-tables
It's called GroovyTables. Located at: https://github.com/tools4j/groovy-tables
它可用于填充类型化的对象列表。例如
It can be used to populate a typed list of objects. e.g.
List<Quote> quotes = GroovyTables.createListOf(Quote).fromTable {
symbol | price | quantity
"AUD/USD" | 1.0023 | 1200000
"AUD/USD" | 1.0024 | 1400000
"AUD/USD" | 1.0026 | 2000000
"AUD/USD" | 1.0029 | 5000000
}
这篇关于从Groovy中的表格数据填充域对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!