一:开发环境:MyEclipse 6.5
原文作者:华丽的痘痘
二:代码:
1.Calculator.inteface
package org.zhang;
public interface Calculator {
public void add(int num);
public void substract(int num);
public void multiply(int num);
public void divide(int num);
public void square(int num);
public void squareRoot(int num);
public void clear();
public int getResult();
}
2.CalculatorImp.class
package org.zhang;
public class CalculatorImp implements Calculator {
private static int result;
public void add(int num) {
result += num;
}
public void clear() {
result = 0;
}
public void divide(int num) {
result /= num;
}
public int getResult() {
return result;
}
public void multiply(int num) {
}
public void square(int num) {
result = num * num;
}
public void squareRoot(int num) {
for (;;)
;
}
public void substract(int num) {
result -= num;
}
}
3.CalculatorTest.class
package org.zhang;
import static org.junit.Assert.assertEquals;
import java.util.Arrays;
import java.util.Collection;
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class CalculatorTest {
private static Calculator calculator = new CalculatorImp();
private int param;
private int result;
@Before
public void setUp() throws Exception {
calculator.clear();
}
@Parameters
public static Collection data() {
return Arrays.asList(new Object[][] { { 2, 4 }, { 0, 0 }, { -3, 9 },
});
}
public CalculatorTest(int param, int result) {
this.param = param;
this.result = result;
}
@Test
public void square() {
calculator.square(param);
assertEquals(result, calculator.getResult());
}
// @Test
// public void testAdd() {
// calculator.add(2);
// calculator.add(3);
// assertEquals(5,calculator.getResult());
// }
//
// @Test(expected=ArithmeticException.class)//Test the method throw
// ArithmeException.
// public void testDivide() {
// calculator.add(10);
// calculator.divide(0);
// assertEquals(5,calculator.getResult());
// }
// @Ignore
// public void testMultiply() {
//
// }
//
// @Test(timeout=1000)
// public void testSquareRoot(){
// calculator.squareRoot(4);
// assertEquals(2,calculator.getResult());
// }
//
// @Test
// public void testSubstract() {
// calculator.add(10);
// System.out.println(calculator.getResult());
// calculator.substract(2);
// System.out.println(calculator.getResult());
// assertEquals(8,calculator.getResult());
// }
}
4.AllCalculatorTest.class
package org.zhang;
import org.junit.runner.RunWith;
import org.junit.runners.Suite;
@RunWith(Suite.class)
@Suite.SuiteClasses( { CalculatorTest.class })
public class AllCalculatorTest {
}