Question

Have been using Spock a fair bit, and really like the ability to use tables in tests for input/output scenarios.

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.

Was it helpful?

Solution 2

I've written an API which addresses my own question.

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
}

OTHER TIPS

Here is how you do it using Groovy DSL: http://tux2323.blogspot.com/2013/04/simple-table-dsl-in-groovy.html

Using the example in the link

List<Row> rows = TableParser.asListOfRows {
 quantity |    bid |    ask
  1000000 | 1.1220 | 1.2230
  2000000 | 1.1219 | 1.2233
 10000000 | 1.1217 | 1.2234
 15000000 | 1.1216 | 1.2240
}

You can your custom logic to convert Row to Quote

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top