[JAVA] Summary of execution order such as spock setup

When I look around, there are people who are addicted to this, so I thought it would be good if I didn't stumble.

suddenly

spock I won't explain it in detail, but there are some setup cleanups and a place to define test data called where.

Quickly conclude With a table and a picture

Definition timing Remarks
setupSpec test[class]At the beginning of[once]Move equivalent to static
setup test[data] [Every]Moves first
cleanup test[data] [Every]Last move to
cleanupSpec test[class]At the end of[once]Move equivalent to static
where test[Method]At the beginning of[For data]Move equivalent to static

Green letters are static and red letters are others, read from the left

スクリーンショット 2020-04-01 20.32.17.png

So what's the problem

Two big

static Since it is equivalent to static, initialization processing using variables such as @Autowired cannot be called with setupSpec / cleanupSpec.

Cannot be used from where

Be careful as it tends to be done

Execution order

There are many here

Especially in the case of creating test data involving now etc., there are cases where the test data cannot be created as expected and the test can be completed.

For example, if you write code that falsifies the system clock in setup, create test data including now in where, and perform a pattern test. The order is to falsify the system clock after creating the test data, so it does not meet expectations.

In that case, move the setup to setupSpec

If setup cannot be done within static processing, for example, enclosing the data on the where side with{}and adding()on the expect side will delay the execution, but If you want to do something tech with test code ** Most of the time the product code (= design) ** is wrong, so let's refactor it obediently

It's over quickly

Bonus: Code image of the example given in the execution order

In this case, it works in the order of mkData ()-> setClock ()

def setup() {
    setClock()
}

def test() {
    expect:
    sut.f(data) == exp

    where:
    data     || exp
    mkData() || ...
}

Do this

def setupSpec() {
    setClock()
}

def test() {
    expect:
    sut.f(data) == exp

    where:
    data     || exp
    mkData() || ...
}

This will work in the order setClock ()-> mkData ()

def setup() {
    setClock()
}

def test() {
    expect:
    sut.f(data()) == exp

    where:
    data         || exp
    { mkData() } || ...
}

However, for now, for example, it is much easier to test by passing it as an argument than generating it internally in sut.f, so it is better to go back to review the existing construction.

def test() {
    expect:
    sut.f(data, date(2020, 3, 1)) == exp

    where:
    data     || exp
    mkData() || ...
}

Recommended Posts

Summary of execution order such as spock setup
A summary of only Rails tutorial setup related