June 24, 2010

org.scalatest.Spec for Rational

A rational number is a number that can be expressed as a ratio d/n ....

package funobject

import org.scalacheck.Test.check
import org.scalacheck.ConsoleReporter.testReport

import org.scalatest.Spec
import org.scalatest.matchers.ShouldMatchers
import org.scalatest.tools._
import funobject.Rational._
import funobject._

class RationalSpec extends Spec with ShouldMatchers { 
  // shorthand for Rational object
  val R = Rational 

  describe("A Rational Number") { 
    
    it("should throw IllegalArgumentException " +
       "if zero denuminator pased to ctor") { 
      evaluating { val e = R(1, 0) } should produce [IllegalArgumentException]      
    }

    it("should implement +, -, *, / and unary -") { 
      R(1,2) + R(2, 3) should have { 
        'nomer (7)
        'denom (6)
      }

      R(3,2) - R(1, 3) should have { 
        'nomer (7)
        'denom (6)
      }

      R(1, 3) * R(2, 5) should have { 
        'nomer (2)
        'denom (15)
      }

      R(1, 3) / R(2, 5) should have { 
        'nomer (5)
        'denom (6)
      }

      -R(1, 2) should have { 
        'nomer (-1)
        'denom (2)
      }
    }

    it("should have normal form") { 
      R(22, 42) should be === R(11, 21)
    }

    it("should support mixed ariphmetic" +
       " with implicit cast from integer") { 
      R(1,2) / 7 + (1 - R(2,3)) should be === R(-11, 42)
    }
    
    it("should have a total order") { 
      import RationalOrderingCheck._

      check(propertyReflexive)  should be ('passed)
      check(propertySymmetry)   should be ('passed)
      check(propertyTransitive) should be ('passed)
    }
  }
  
}


No comments:

Post a Comment