软件测试实验三
题目二:
public class Calculator{ private static int result=0; // 静态变量,用于存储运行结果 public void setResult(int a){ result=a; } public void add(int n) { result = result + n; } public void substract(int n) { result = result - 1; //故意的Bug,应该是 result =result-n } public void multiply(int n) { result = result * n; } // 假设此方法在项目完成过程中尚未写好 public void divide(int n) { result = result / n; } public void square() { result = result * result; } public void squareRoot() { //求平方根 result = (int)Math.sqrt(result); //Bug : 死循环 } public void clear() { // 将结果清零 result = 0; } public int getResult(){ return result; } }
测试类:
import org.junit.Test; import static org.junit.Assert.assertEquals; public class CalculatorTest { private Calculator calculator=new Calculator(); @Test public void Testadd() throws Exception { calculator.setResult(0); calculator.add(-5); assertEquals(-5, calculator.getResult()); } @Test public void Testsubstract() throws Exception { calculator.setResult(-5); calculator.substract(-5); assertEquals(10, calculator.getResult()); } @Test public void Testmultiply() throws Exception { calculator.setResult(10); calculator.multiply(10); assertEquals(100, calculator.getResult()); } @Test public void Testsquare() throws Exception { calculator.setResult(100); calculator.square(); assertEquals(10000, calculator.getResult()); } @Test public void TestsquareRoot() throws Exception { calculator.setResult(10000); calculator.squareRoot(); assertEquals(100, calculator.getResult()); } @Test public void Testclear() throws Exception { calculator.clear(); assertEquals(0, calculator.getResult()); } }
题目三:
import java.util.Scanner; public class Year { public static int YearJudge(int year){ int result; Scanner sc = new Scanner(System.in); //处理部分 if (year % 4 == 0 && year % 100 !=0 ||year % 400 == 0) { result = 1; }else { result = 0; } //输出部分 return result; } public static void main(String[] args){} }
测试类:
import org.junit.Test; import static org.junit.Assert.assertEquals; public class YearTest { @Test public void TestYearJudge() throws Exception { assertEquals(1, new Year().YearJudge(2012)); } }
题目四:
import java.util.Scanner; public class Triangle { public static int TriangleJudge(int a,int b,int c){ int flag=0; if(a+b<=c||a+c<=b||b+c<=a){ flag=0; }else{ if(a==(int)((a+b+c)/3)){ flag=3; }else if(a!=b&&b!=c&&a!=c){ flag=1; }else{ flag=2; } } return flag; } }
测试类:
import org.junit.Test; import static org.junit.Assert.assertEquals; public class TriangleTest { @Test public void TestTriangleJudge() throws Exception { assertEquals(2, new Triangle().TriangleJudge(1,3,3)); } }