对Triangle进行JUnit测试并设计测试用例使其满足100%语句覆盖并把Java代码给我
时间: 2024-02-12 22:09:06 浏览: 78
软件测试实验一
好的,以下是Triangle类的Java代码和JUnit测试代码:
Triangle.java
```java
public class Triangle {
private double side1, side2, side3;
public Triangle(double side1, double side2, double side3) {
this.side1 = side1;
this.side2 = side2;
this.side3 = side3;
}
public String getType() {
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
return "Not a triangle";
}
if (side1 + side2 <= side3 || side1 + side3 <= side2 || side2 + side3 <= side1) {
return "Not a triangle";
}
if (side1 == side2 && side2 == side3) {
return "Equilateral";
}
if (side1 == side2 || side1 == side3 || side2 == side3) {
return "Isosceles";
}
return "Scalene";
}
}
```
TriangleTest.java
```java
import org.junit.Test;
import static org.junit.Assert.assertEquals;
public class TriangleTest {
@Test
public void testEquilateralTriangle() {
Triangle t = new Triangle(2, 2, 2);
assertEquals("Equilateral", t.getType());
}
@Test
public void testIsoscelesTriangle() {
Triangle t = new Triangle(2, 2, 3);
assertEquals("Isosceles", t.getType());
}
@Test
public void testScaleneTriangle() {
Triangle t = new Triangle(3, 4, 5);
assertEquals("Scalene", t.getType());
}
@Test
public void testNotATriangle1() {
Triangle t = new Triangle(0, 2, 3);
assertEquals("Not a triangle", t.getType());
}
@Test
public void testNotATriangle2() {
Triangle t = new Triangle(1, 2, 3);
assertEquals("Not a triangle", t.getType());
}
@Test
public void testNotATriangle3() {
Triangle t = new Triangle(2, 2, 4);
assertEquals("Not a triangle", t.getType());
}
}
```
这里我们设计了6个测试用例,分别测试了等边三角形、等腰三角形、不等边三角形和非三角形的情况,以覆盖Triangle类中所有的语句。
注:由于输入为double类型,存在精度问题,因此在实际使用时可能需要根据实际情况进行修改。
阅读全文