Search code examples
scalatestingcase-class

Scala case classes test


I define a sealed trait shape with case class Point and LineSegment and have a behaviour for the class LineSegment which tells me if the two LineSegments intersect, however when I try to test that behavior.. it says it cannot recognize it in the test suite.

sealed trait Shape
case class Point(x: Int, y: Int) extends Shape {
//require(x != null & y !=null, "null values for point")
}

case class LineSegment(point1: Point, point2: Point)  extends Shape {
 require(point1 != point2)

 def intersect(lineSegment1: LineSegment, lineSegment2:LineSegment): 
 Boolean ={
// val A1, A2, B1, B2, C1, C2
val A1 = lineSegment1.point2.y - lineSegment1.point1.y
val B1 = lineSegment1.point1.x - lineSegment1.point2.x
val C1 = A1 * lineSegment1.point1.x + B1 * lineSegment1.point1.y

val A2 = lineSegment2.point2.y - lineSegment2.point1.y
val B2 = lineSegment2.point1.x - lineSegment2.point2.x
val C2 = A2 * lineSegment2.point1.x + B2 * lineSegment2.point1.y

val det = A1 * B2 - A2 * B1
if(det == 0)
  return false
else
  return true

}

}

This is the test I am trying to do

import model.Point
import model.LineSegment
import org.scalatest.{FlatSpec, ShouldMatchers}

 class LineIntersectionTest extends FlatSpec with ShouldMatchers{
 val point1 = Point(20,30);
 val point2 = Point(10,35);
 val point3 = Point(100,10);
 val point4 = Point(16,45);

 val lineSegment1 = LineSegment(point1,point2);
 val lineSegment2 = LineSegment(point3,point4);

  "LineSegmentIntersection Behaviour" should "work for a line segment"  
  in {
  intersect(lineSegment1, lineSegment2) should be (true)
   }}

but I get an error cannot resolve symbol intersect, cannot resolve symbol should.. it's not recognizing the method intersect

what am I doing wrong in here?


Solution

  • You're using intersect as if it was a function on the LineIntersectionTest class. The following should work:

    lineSegment1.intersect(lineSegment1, lineSegment2) should be (true)
    

    However I would probably use a different implementation. Maybe:

    object LineUtils {
      def intersect(l1: LineSegment, l2: LineSegment): Boolean
    }
    
    // Usage
    LineUtils.insersect(lineSegment1, lineSegment2)