对Triangle进行JUnit测试并设计测试用例使其满足100%函数覆盖、语句覆盖和判定覆盖并把Java代码给我
时间: 2024-02-07 07:03:01 浏览: 117
JUnit测试代码示例
4星 · 用户满意度95%
好的,这是Triangle类的Java代码:
```
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle(double s1, double s2, double s3) {
side1 = s1;
side2 = s2;
side3 = s3;
}
public boolean isTriangle() {
if (side1 <= 0 || side2 <= 0 || side3 <= 0) {
return false;
}
if (side1 + side2 <= side3 || side1 + side3 <= side2 || side2 + side3 <= side1) {
return false;
}
return true;
}
public String getType() {
if (!isTriangle()) {
return "Not a triangle";
}
if (side1 == side2 && side2 == side3) {
return "Equilateral triangle";
} else if (side1 == side2 || side1 == side3 || side2 == side3) {
return "Isosceles triangle";
} else {
return "Scalene triangle";
}
}
}
```
下面是满足100%函数覆盖、语句覆盖和判定覆盖的JUnit测试用例:
```
import org.junit.Test;
import static org.junit.Assert.*;
public class TriangleTest {
@Test
public void testIsTriangle() {
// Test invalid triangles
Triangle t1 = new Triangle(-1, 2, 3);
assertFalse(t1.isTriangle());
Triangle t2 = new Triangle(1, -2, 3);
assertFalse(t2.isTriangle());
Triangle t3 = new Triangle(1, 2, -3);
assertFalse(t3.isTriangle());
Triangle t4 = new Triangle(0, 1, 2);
assertFalse(t4.isTriangle());
Triangle t5 = new Triangle(1, 2, 3);
assertFalse(t5.isTriangle());
// Test valid triangles
Triangle t6 = new Triangle(3, 4, 5);
assertTrue(t6.isTriangle());
Triangle t7 = new Triangle(3, 3, 3);
assertTrue(t7.isTriangle());
Triangle t8 = new Triangle(1, 2, 2);
assertTrue(t8.isTriangle());
}
@Test
public void testGetType() {
// Test invalid triangles
Triangle t1 = new Triangle(-1, 2, 3);
assertEquals("Not a triangle", t1.getType());
Triangle t2 = new Triangle(1, -2, 3);
assertEquals("Not a triangle", t2.getType());
Triangle t3 = new Triangle(1, 2, -3);
assertEquals("Not a triangle", t3.getType());
Triangle t4 = new Triangle(0, 1, 2);
assertEquals("Not a triangle", t4.getType());
Triangle t5 = new Triangle(1, 2, 3);
assertEquals("Not a triangle", t5.getType());
// Test valid triangles
Triangle t6 = new Triangle(3, 4, 5);
assertEquals("Scalene triangle", t6.getType());
Triangle t7 = new Triangle(3, 3, 3);
assertEquals("Equilateral triangle", t7.getType());
Triangle t8 = new Triangle(1, 2, 2);
assertEquals("Isosceles triangle", t8.getType());
}
}
```
阅读全文