0

I'm searching for a way to have a parameterized test based on the content of a folder Since it's an Android test I am a bit limited in the test tools I can use

Idea is: i add a file to the folder -> one more test

vanleeuwenbram
  • 1,289
  • 11
  • 19

1 Answers1

0

It doesn't look much different from any other parametrized test (@ParametrizedTest). The sample program can look like this (for simplicity everything is in one file):

class SomeFunction {
    fun doStuff(parameter: String): Int {
        return parameter.length // production code to be tested
    }
}

class SomeFunctionTest {

    companion object {
        @JvmStatic
        fun testData(): Collection<String> {
            // for simplicity of the demo reading the whole file into string
            return File("testfolder").listFiles().map { it.readText() }
        }
    }

    @ParameterizedTest
    @MethodSource("testData")
    fun testDoStuff(testInput: String) {
        println("running test: $testInput")
        assertEquals(testInput.length, SomeFunction().doStuff(testInput))
    }
}

You source your test data from a testfolder. If you want to get the data not from the file api but rather as classpath resources - that's another story - there are some suggestions like this: Get a list of resources from classpath directory

Daniil
  • 88
  • 1
  • 8
  • Indeed, had to tweak it a bit for my case linked with android but this helped a lot @JvmStatic @Parameterized.Parameters(name = "{0}") fun data() = InstrumentationRegistry.getInstrumentation().context.assets.list("folder")!! .filterNot { it.endsWith(".json") } .map { arrayOf(it.substring(0, it.lastIndexOf(".")), it.endsWith(".pdf")) } – vanleeuwenbram Jun 13 '23 at 06:37