Search code examples
kotlinspek

Constants in Kotlin Spek Tests


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
})

Solution

  • 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)
    
    })