这是我为netbeans生成测试用例创建junit测试和自动化junit的代码,但我现在不知道如何进行测试,如果你们可以请给我一个例子。
class Account
{
private double balance=100;
private String accountNumber;
private boolean firstTime=true;
public void deposit(double howMuch)
{
if(howMuch>0)
{
balance=balance+howMuch;
System.out.println(howMuch+ "was successfully deposited into your account" + "The new balance of your account "+balance);
}
else
{
System.err.println("Please do not enter negative values");
}
}
}
这是junit测试类,请告诉我如何更改null值并运行testCase。
package BankSys;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import static org.junit.Assert.*;
/**
*
* @author SweAtBAr
*/
public class AccountTest {
public AccountTest() {
}
@BeforeClass
public static void setUpClass() {
}
@AfterClass
public static void tearDownClass() {
}
@Before
public void setUp() {
}
@After
public void tearDown() {
}
/**
* Test of deposit method, of class Account.
*/
@Test(expected=NullPointerException.class)
public void testDeposit() {
System.out.println("deposit");
double howMuch = 0.0;
Account instance = null;
instance.deposit(howMuch);
// TODO review the generated test code and remove the default call to fail.
fail("The test case is a prototype.");
}
答案 0 :(得分:0)
在方法testDeposit()中,您应该实例化'实例'类型帐户。
Account instance = new Account();
您可以添加一个初始化帐号和余额(帐户类属性)的附加构造函数:
public class Account
{
private double balance;
private String accountNumber;
private boolean firstTime;
public void deposit(double howMuch)
{
if(howMuch>0)
{
balance=balance+howMuch;
System.out.println(howMuch+ "was successfully deposited into your account" + "The new balance of your account "+balance);
}
else
{
System.err.println("Please do not enter negative values");
}
}
public Account(final String accountNumber, final double balance) {
this.accountNumber = accountNumber;
this.balance = balance;
this.firstTime = true;
}
public Account() {}
public double getBalance() {
return balance;
}
public void setBalance(final double balance) {
this.balance = balance;
}
// Add here setters/getters for accountNumber and firstTime
}
接下来在您的测试方法中,您必须在完成存款后检查余额值是否正确:
instance.deposit(howMuch);
assertEquals(expectedValue, instance.getBalance());
答案 1 :(得分:0)
删除(expected=NullPointerException.class)
,如果您不希望存款方法会抛出NullPointerException。
简单的测试用例是:
@Test
public void testDeposit() {
System.out.println("deposit");
double howMuch = 1.0;
Account instance = new Account();
instance.deposit(howMuch);
// As mentioned by Olivier Meurice, you may have a method to get the balance
// To test whether the account balance is correct
assertEquals(1.0, instance.getBalance());
}