Suche…


Word Count Unit Test (Scala + JUnit)

Zum Beispiel haben wir WordCountService mit der countWords Methode:

class WordCountService {
    def countWords(url: String): Map[String, Int] = {
        val sparkConf = new SparkConf().setMaster("spark://somehost:7077").setAppName("WordCount"))
        val sc = new SparkContext(sparkConf)
        val textFile = sc.textFile(url)
        textFile.flatMap(line => line.split(" "))
                .map(word => (word, 1))
                .reduceByKey(_ + _).collect().toMap
    }
}

Dieser Service scheint sehr hässlich und nicht für Unit-Tests geeignet. SparkContext sollte in diesen Dienst eingefügt werden. Es kann mit Ihrem bevorzugten DI-Framework erreicht werden. Zur Vereinfachung wird es jedoch mithilfe des Konstruktors implementiert:

class WordCountService(val sc: SparkContext) {
    def countWords(url: String): Map[String, Int] = {
        val textFile = sc.textFile(url)
        textFile.flatMap(line => line.split(" "))
                .map(word => (word, 1))
                .reduceByKey(_ + _).collect().toMap
    }
}

Jetzt können wir einen einfachen JUnit-Test erstellen und testbaren sparkContext in WordCountService einführen:

class WordCountServiceTest {
    val sparkConf = new SparkConf().setMaster("local[*]").setAppName("WordCountTest")
    val testContext = new SparkContext(sparkConf)
    val wordCountService = new WordCountService(testContext)

    @Test
    def countWordsTest() {
        val testFilePath = "file://my-test-file.txt"

        val counts = wordCountService.countWords(testFilePath)

        Assert.assertEquals(counts("dog"), 121)
        Assert.assertEquals(counts("cat"), 191)
    }
}


Modified text is an extract of the original Stack Overflow Documentation
Lizenziert unter CC BY-SA 3.0
Nicht angeschlossen an Stack Overflow