Programming

All about programming stuff

by anvie

Contoh cara buat test case secara dinamis menggunakan Scala + Spec2, dalam contoh ini saya menggunakan Spec2 versi 2.4:

class RfcSpec extends mutable.Specification {
    "RFC Spec" should {
        examplesBlock {
            val dataFile = Source.fromURL(getClass.getResource("/rfc-test.txt"))
            val (inputs, outputs) = dataFile.getLines().partition(p => p.startsWith(">"))
            val data = inputs.map(_.stripPrefix("> ")).zip(outputs.map(_.stripPrefix(": ")))
            for ((in, out) <- data){
                s"`$in` -> `$out`" in {
                    translate(in) must_== out
                }
            }
        }
    }

    private def translate(in:String) = {
        Translator.translate(in)
    }
}

Kode ini kalau dijalankan (dan bener) kira-kira outputnya seperti ini:

[info] Compiling 1 Scala source to .../target/test-classes...
[info] RfcSpec
[info]
[info] RFC Spec should
[info] + `gw suka` -> `saya suka`
[info] + `jancuk itu orang` -> `kurang ajar itu orang`
[info] + `ra jelas` -> `tidak jelas`
[info] + `syantik aku lg pusyinggg` -> `cantik aku sedang pusing`
[info]
[info] Total for specification RfcSpec
[info] Finished in 13 ms
[info] 7 examples, 0 failure, 0 error
[info] Passed: Total 7, Failed 0, Errors 0, Passed 7

Semoga bermanfaat.

Happy coding!