Scala程式設計程式中的測試小框架
阿新 • • 發佈:2018-12-25
package com.AtomicTest
import java.io.FileWriter
/**
* A tiny little testing framework,to display results and to introduce & promote
* unit testing early in the learning curve.To use in a script or App, include:
* import com.AtomicTest.AtomicTest._
* Created by cyz on 2016/12/27.
*/
object AtomicTest {
implicit def any2Atomic[T](target: T) = {
new AtomicTest(target)
}
class AtomicTest[T](val target: T) {
val errorLog = "_AtomicTestErrors.txt"
def tst[E](expected: E)(test: => Boolean) {
println(target)
if (test == false) {
val msg = "[Error] expected:\n" + expected
println(msg)
val el = new FileWriter(errorLog, true)
el.write(target + msg + "\n")
el.close()
}
}
def str = Option(target).getOrElse("").toString
//Safely convert to a String
def is(expected: String) = tst(expected) {
expected.replaceAll("\r\n" , "\n") == str
}
def is[E](expected: E) = tst(expected) {
expected == target
}
def beginWith(exp: String) = tst(exp) {
str.startsWith(exp.replaceAll("\r\n", "\n"))
}
}
}
上述是測試小框架原始碼,打包之後就可以匯入到自己所寫的程式中利用“is” 關鍵字來在程式內部測試程式碼是否達到自己想要的結果,打包方式見IntelJ IDEA的打包方法