0

I want to add some constants to my Spek test to hold the filenames of some resource files that the tests will access like this.

What is the idiomatic way to do this?

In JUnit, I would declare a static final value. But in Spek, I can't even use the typical kotlin idoim of a companion object to hold them as Spek tests are objects themselves, which can't have companions. I can't even mark them as const as I get the error "Modifier 'const' is not applicable to 'local variable'.

So is there any better or more preferred way than this:

object MyTest : Spek({
   val SAMPLE_GRAPH_FILENAME1 = "sample_graph1.png"
   val SAMPLE_GRAPH_FILENAME2 = "sample_graph2.png"
   val SAMPLE_OTHER_FILENAME = "sample_data.txt"

   // test code
})
Tom Tresansky
  • 19,364
  • 17
  • 93
  • 129

1 Answers1

1

You could place the constants inside the body of this object, although then you'd have to prefix them with the name of the object to access them:

object MyTest : Spek({

    println(MyTest.SAMPLE_GRAPH_FILENAME1)

}) {
    const val SAMPLE_GRAPH_FILENAME1 = "sample_graph1.png"
}

Alternatively, you could have another object hold these constants, or just make them package (or file, with private) scoped:

const val SAMPLE_GRAPH_FILENAME1 = "sample_graph1.png"

object MyTest : Spek({

    println(SAMPLE_GRAPH_FILENAME1)

})
zsmb13
  • 85,752
  • 11
  • 221
  • 226
  • Either would work, as would leaving them as is. But which is preferred, and why? – Tom Tresansky Apr 05 '18 at 17:27
  • If you can put it somewhere where it can be a `const`, it'll be inlined for a small performance improvement. Otherwise - it's your code, use whichever form looks good for your eyes. There's no significant difference, it's just a matter of organization. – zsmb13 Apr 05 '18 at 17:44