使用java语言编写一个类,该类用于完成简单的数学四则运算。 使用Junit单元测试方法对编写的类进行测试。
Math.java
public class Math {
public int add ( int a, int b) {
return a + b;
}
public int min ( int a, int b) {
return a - b;
}
public int mui ( int a, int b) {
return a * b;
}
public int div ( int a, int b) throws Exception{
if ( b== 0 ) {
throw new Exception ( "除数不能为0" ) ;
}
return a/ b;
}
}
MathTest.java
public class MathTest {
Math math= new Math ( ) ;
@Test
public void addTest ( ) {
assertEquals ( 3 , math. add ( 1 , 2 ) ) ;
}
@Test
public void minTest ( ) {
assertEquals ( - 1 , math. min ( 1 , 2 ) ) ;
}
@Test
public void muiTest ( ) {
assertEquals ( 2 , math. mui ( 1 , 2 ) ) ;
}
@Test
public void testDiv ( ) {
int result= 0 ;
try {
result = math. div ( 6 , 2 ) ;
}
catch ( Exception e) {
e. printStackTrace ( ) ;
}
assertEquals ( 3 , result) ;
}
@Test
public void testDiv1 ( ) {
Throwable throwable= null;
Math math= new Math ( ) ;
try {
int result= math. div ( 6 , 0 ) ;
}
catch ( Exception e) {
throwable= e;
}
assertNotNull ( throwable) ;
assertEquals ( Exception. class , throwable. getClass ( ) ) ;
assertEquals ( "除数不能为0" , throwable. getMessage ( ) ) ;
}
}