测试无返回值的模块
import junit.framework.TestCase;
import org.junit.Test;
import java.io.ByteArrayOutputStream;
import java.io.PrintStream;
import static org.hamcrest.CoreMatchers.containsString;
import static org.junit.Assert.assertThat;
public class BankAccountTest extends TestCase {
BankAccount b = new BankAccount("1", "zhangsan", "10", "123456");
@Test
public void testDeposit(){
//重定向输出到outputContent
final ByteArrayOutputStream outputContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outputContent));
int n = 10;
b.Deposit(n);
assertThat(outputContent.toString(), containsString("Deposited money successed, the total money is :" + n));
n = -2;
b.Deposit(n);
//获取输出并进行字符串匹配
assertThat(outputContent.toString(), containsString("Failed to deposite, money should be larger than 0"));
}
@Test
public void testWithDraw(){
final ByteArrayOutputStream outContent = new ByteArrayOutputStream();
System.setOut(new PrintStream(outContent));
int n = 10;
b.Deposit(n);
b.WithDraw(n);
assertThat(outContent.toString(), containsString("You have withdrawed money:"));
b.WithDraw(10);
assertThat(outContent.toString(), containsString("Error!"));
}
@Test
public void testWithdraw(){
BankAccountGold b = new BankAccountGold("2222","aaa","111","222");
final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
System.setOut(new PrintStream(byteArrayOutputStream));
int n = 100;
int m = 50;
b.Deposit(n);
b.WithDraw(m);
assertThat(byteArrayOutputStream.toString(), containsString("Succeed to withdraw. your balance is :" + (n - m)));
b.WithDraw(50);
assertThat(byteArrayOutputStream.toString(), containsString("Succeed to withdraw. your balance is :" + (0)));
b.WithDraw(999);
assertThat(byteArrayOutputStream.toString(), containsString("Succeed to withdraw. your balance is :" + (-999)));
b.WithDraw(1);
assertThat(byteArrayOutputStream.toString(), containsString("Failed to withdraw ,you cannot overdraft more than 1000!"));
}
}Last updated