14장 assertions and unit testing - codeport/scala GitHub Wiki

14.1 Assertions

###kingori

  • predefined method assert가 제공됨 ( in Predef)
assert(condition) // throws AssertionError when condition does not hold
asssert(condition, explanation) // throws AssertionError contains explanation when condition does not hold
  • ensuring도 있음 ( in Predef)
scala> def a( value: Int ): Int =  {   { value; } ensuring( value > 2 ); }
a: (value: Int)Int

scala> a(4)
res5: Int = 4

scala> a(2)
java.lang.AssertionError: assertion failed   
  • java와 마찬가지로 -ea, -da 로 assert 문을 켜고 끌 수 있음

14.2 Unit testing in Scala

###kingori

  • JUnit, TestNG 등의 java 도구, ScalaTest, specs, ScalaCheck 등의 scala 도구를 사용할 수 있음

  • 이번 장은 이들 도구 사용방법을 소개함

  • ScalaTest

    • 모양은 JUnit 3.X 랑 비슷한 듯?
import org.scalatest.Suite
import Element.elem

class ElementSuite extends Suite {
   def testUniformElement() {
     val ele = elem('x',2,3)
     assert( ele.width == 2)
   }
}

scala> (new ElementSuite).execute()
  • FunSuite를 이용한 function value 형태도 가능 (Fun means Function)
import org.scalatest.FunSuite
import Element.elem

class ElementSuite extends FunSuite {
  test("elem result should have passed width") {  //test name
     val ele = elem('x',2,3)
     assert( ele.width == 2)
  }
} 

14.3 Imformative failure reports

###kingori

scalaTest에서 error를 내는 방법

assert(ele.width === 2 ) //triple =
expect(2) {  //expected, actual distinction
 ele.width 
}
intercept[IllegalArgumentException] { //expected exception. if code does not throw exception, intercept throws TestFailedException 
 elem('x', -2, 3) 
}

14.4 Using JUnit and TestNG

###kingori

  • junit 3.8을 쓰더라도 scalaTest의 assert 문을 사용할 수 있음.
  • JUnit3Suite 가 ScalaTest의 Suite trait를 mixin하고 있기 때문에 ScalaTest의 runner로 실행 가능함
  • annotation 기반의 junit 4.x, TestNG도 OK

14.5 Tests as specifications

###kingori

  • BDD style - ScalaTest는 Spec, WordSpec, FlatSpec, FeatureSpec 등의 trait 제공
    • matcher DSL도 제공됨
"Subject" should "behavior" in {
   val ele = elem('x',2,3)
   ele.width should be (2)
}
it should ...
it should "behavior" in {
   evaluating {
     ...
   } should produce [IllegalArgumentException]
}
  • specs - 이것까지 알 필요가?

14.6 Property-based testing

###kingori

  • ScalaCheck - test가 준수해야 할 속성 명기. Checkers trait가 check 메서드를 제공함
    • ==> : ScalaCheck의 implication operator. 왼쪽이 true면 오른쪽도 true여야 함.
class ElementSepc extends WordSpec with Checkers {
  "elem result" must {
    "have passed width" in {
      check( (w: Int) => w > 0 ==> (elem('x', w, 3).width == w))
    }
   ...
  }
}

14.7 Organizing and running tests

###kingori

ScalaTest의 테스트 구성

  • Suites 안에 큰 test suites를 nesting 함
    • manual nesting: Suites.nestedSuites 를 override하거나, SuperSuite의 생성자에 Suite를 넘김
    • automatic nesting: ScalaTest의 Runner에 package 이름을 명시.
  • 실행은 ScalaTest의 Runner Application을 이용함.
scala -cp ~~~ org.scalatest.tools.Runnner -p {runpath - JAR file contains the suite classes} -s {suite to execute}

14.8 Conclusion

###kingori

skip