发布网友 发布时间:2022-04-22 08:57
共1个回答
热心网友 时间:2024-01-15 12:36
以下以银行余额、存款、取款为例
一、Junit配置
Junit同Eclipse一同提供,无需下载。要使用Junit必须先将Junit jar 保存在项目的build路径上,并创建一个测试类,步骤如下:
1)法一:
法二:点击项目test001,右键-propreties
2)选择Libraries,点击Add variable按钮,输入变量名JUNIT_LIB,路径:E:\测试\测试工具\Juint\eclipse\eclipse-jee-kepler-SR2-win32\eclipse\plugins\org.junit_4.11.0.v201303080030,结果如下图:
二、编写测试类和代码、执行测试用例
1)新建测试类:New-Junit Test Case
2)编写测试代码:
1 package testsample; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import junit.framework.TestCase; 6 public class Tc_Account extends TestCase { 7 8 public Tc_Account(String arg0) 9 {10 super(arg0);11 }12 @Before13 public void setUp() throws Exception {14 super.setUp() ;15 }16 public void testDeposit(){17 Account account=new Account();18 assertEquals("Account should start with no funds.",1,account.balance());19 20 account.deposit(5);21 assertEquals("Account should reflect deposit.", 7, account.balance());22 }23 24 public void testwithdraw(){25 Account account=new Account();26 account.deposit(5);27 account.withdraw(3);28 assertEquals("Account should reflect withdarw.", 3, account.balance());29 }30 31 @After32 public void tearDown() throws Exception {33 super.tearDown();34 }35 }
View Code
3)新建Acoount类,实现银行的余额、存款、取款:
1 package testsample; 2 3 public class Account { 4 protected int balance; 5 public int balance(){ 6 return balance;
7 } 8 public void deposit(int amount){ 9 balance+=amount;10 }11 public void withdraw(int amount){12 balance-=amount;13 }14 }
View Code
4)执行测试用例:右键项目testsample-Run as-Junit Test Case,通过failure trace可以查看错误信息
5)调整测试用例中的预期值:
1 package testsample; 2 3 import org.junit.After; 4 import org.junit.Before; 5 import junit.framework.TestCase; 6 public class Tc_Account extends TestCase { 7 8 public Tc_Account(String arg0) 9 {10 super(arg0);11 }12 @Before13 public void setUp() throws Exception {14 super.setUp() ;15 }16 public void testDeposit(){17 Account account=new Account();18 assertEquals("Account should start with no funds.",0,account.balance());19 20 account.deposit(5);21 assertEquals("Account should reflect deposit.", 5, account.balance());22 }23 24 public void testwithdraw(){25 Account account=new Account();26 account.deposit(5);27 account.withdraw(3);28 assertEquals("Account should reflect withdarw.", 2, account.balance());29 }30 31 @After32 public void tearDown() throws Exception {33 super.tearDown();34 }35 }
View Code
6)执行测试用例,结果如下:所有测试通过