字數單元測試(Scala JUnit)

例如,我們有 WordCountServicecountWords 方法:

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

這項服務看起來非常難看,不適合單元測試。應該將 SparkContext 注入此服務。可以使用你最喜歡的 DI 框架訪問它,但為了簡單起見,它將使用建構函式實現:

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

現在我們可以建立簡單的 JUnit 測試並將可測試的 sparkContext 注入 WordCountService:

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