如何使用Spock和groovy测试下面的代码?

问题描述 投票:-1回答:1

[我是新手,我被要求开发以下代码,并使用spock和groovy放置测试用例。我不知道要用groovy调用类来检查raddiff Xdiff Y等每个操作的输出]等。请帮助我。

public static void main(String[] args) {
    RectangularShape rectangularShape
    rectangularShape = new Rectangle2D.Double(10,20,30,50)
    Rectangle2D rectangle = rotateRect(rectangularShape,30)
    println(rectangle)
}

static Rectangle2D rotateRect (RectangularShape rect, int angle, Point2D  pivot = null )
{
    if (pivot == null)
    {
        pivot = new Point2D.Double(rect.x + (int) Math.round(rect.width / 2d), rect.y + (int) Math.round(rect.height / 2d))
    }
    double rad = angle * Math.PI / 180;
    double diffX = rect.x - pivot.x
    double diffY = rect.y - pivot.y
    int x = (int) Math.round(rect.x - diffX + (diffX * Math.cos(rad)) + (diffY * Math.sin(rad)))
    int y = (int) Math.round(rect.y - diffY + (diffY * Math.cos(rad)) - (diffX * Math.sin(rad)))
    return new Rectangle2D.Double(x, y, rect.width, rect.height)
}
testing groovy spock groovyshell spock-spy
1个回答
0
投票

第一个要问的问题是“您想在这里测试谁?”>

IMO,您应该测试rotateRect方法的代码(它正确完成了数学计算)。如果是这样,您可以执行以下操作:

class Rectangle2DSpec extends Specification {

   def "rotation works as expected when pivot is null"() {

      given:
          def rect = new Rectangle2D.Double(10,20,30,50)
      when:
          def actual = rotate(rect, null)
      then:
         // check that actual is a correct rectangle with correct coordinates
   }

   def "rotation works as expected when pivot is specified"() {
      given:
          def rect = new Rectangle2D.Double(10,20,30,50)
          def pivot = ...
      when:
          def actual = rotate(rect, pivot)
      then:
         // check that actual is a correct rectangle with correct coordinates
   }  

}

现在,这是Spock测试的最基本的基础,您可以通过使用参数化测试来改进测试,并例如检查不同枢轴的结果。

© www.soinside.com 2019 - 2024. All rights reserved.