1

我正在尝试进行功能测试以检查三角形。我有三个 int 输入。三个输入变量分别描述了三角形每一边的长度。三角形边长应小于或等于 1000。此方法的输出将是 5 个可能值之一:1 表示不等边三角形,2 表示等腰三角形,3 表示等边三角形,4 表示不描述三角形的值,5 表示超出范围的值。

这是我写的第一个测试,但我不知道它是否正确。

public class TriangleTypeFunctionalTest {
    @Before
    public void setUp() throws Exception {
    }

    @Test
    public void testTriangleScalene(x,y,z) {
        if(x < 1000 and y <1000 and z< 1000){
            if ( ( x != y ) and ( x != z ) and ( y !=z ) )  
                return True;
            else
                return False;
        }
        else
            return False;

    }

}

我需要一些帮助理解以及如何做到这一点

4

3 回答 3

2

首先,您需要知道三个数字是三角形边的条件。他们是:

// Sides a, b, c
a + b > c
b + c > a
c + a > b
a > 0
b > 0
c > 0

接下来,您需要一种方法来区分不同类型的三角形。数字代码不是要走的路。

enum TriangleType {
    EQUILATERAL,
    ISOSCELES,
    SCALENE,
    INVALID,
    OVERSIZE
}

接下来,您要编写一个类来测试三个值是否是三角形的边。事实上,Triangle自己做,但不要写类型方法,因为你想做测试驱动开发。

public class Triangle {
    int a;
    int b;
    int c;
    public Triangle(int a, int b, int c) {...}
    public TriangleType type() {
        return null;
        // Not really written yet.
    }
}

现在,您想为type() 您编写测试,然后进行编辑type(),直到您的测试成功。让我们从积极的一面开始。

public class TypeTest {
    @Test
    public void negativeSideAFails() {
        Triangle t = new Triangle(-10, 10, 20);
        Assert.assertEquals(TriangleType.INVALID, t.type());
    }
}

您也应该为 b 面和 c 面编写类似的测试。如果两个值不相等,assertEquals 方法将抛出异常,JUnit 测试运行程序会将其转换为测试失败。

编辑您的type方法直到这些工作,然后继续测试其他条件:

    @Test
    public void sideAMustBeShorterThanSumOfOtherTwo() {
        Triangle t = new Triangle(100, 10, 20);
        Assert.assertEquals(TriangleType.INVALID, t.type());
    }

然后,为代表所有TriangleTypes.

您将有很多测试,但您可以在以后了解@Parameterized测试时对其进行简化。

于 2013-05-24T00:08:49.853 回答
0

为了有一个三角形,每条边都应该低于其他两条边的总和。(我建议你使用 JUnit4)。您只需将(x, y, z)trey 的条件传递给该assertTrue方法。

import static org.junit.Assert.assertTrue;
import org.junit.Test;

public class TriangleTypeFunctionalTest {
   private int x;
   private int y;
   private int z;

   @Before
   public void setUp() throws Exception {
       x = //some mock value;
       y = //some mock value;
       z = //some mock value;
   }

   @Test
   public void testTriangleScalene() {
       assertTrue((x < 1000 && y <1000 && z< 1000));
       assertTrue(( x + y > z) && (x + z > y) && (y + z > x));
   }
}
于 2013-05-23T23:47:26.753 回答
0

为使您拥有三角形,一侧的长度必须小于其他两侧的总和

尝试:

if(x+y<z) //not a triangle
if(x+z<y) //not a triangle

...

我已经有一段时间没有学习数学了,但这应该可以解决问题

于 2013-05-23T23:44:35.903 回答