【发布时间】:2017-10-31 03:47:11
【问题描述】:
这是我还需要在 JUnit 测试用例中测试的 BankAccount 类的一部分。
以下内容来自我的 BankAccount 类,涉及 JUnit 测试用例:
int accountType;
public int getAccountType() {
return accountType;
}
public void setAccountType(int accountType) {
this.accountType = accountType;
}
//getting variable to determine interest rate according to account type
public double getInterestRate(double r) {
double a;
if(getAccountType()==1.0) {
a = 0.5;
}
else if(getAccountType()==2.0) {
a = 4.5;
}
else if(getAccountType()==3.0) {
a = 1.0;
}
else if(getAccountType()==4.0) {
a = 15;
}
else {
a = 0;
}
return a;
}
String type() {
if(getAccountType()==1) {
return "Savings";
}
else if(getAccountType()==2) {
return "Award Savers";
}
else if(getAccountType()==3) {
return "Checking";
}
else if(getAccountType()==4) {
return "Credit Card";
}
else {
return "None";
}
}
//getting the account type from the user
System.out.println("Enter a number from 1 to 4 according to your account type: ");
System.out.println("1 --> Savings");
System.out.println("2 --> Award Savers");
System.out.println("3 --> Checking");
System.out.println("4 --> Credit Card");
bank.setAccountType(scan.nextInt());
//printing the account type back to the user
System.out.println("Account Type: " + bank.type());
现在这是我实际的 J-Unit 测试用例。我已经对此做了很多修改,到目前为止,我能让测试用例成功的唯一方法是,如果我将预期结果(对于帐户类型 1)设置为 0,而它应该是 0.5。
package test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import core.BankAccount;
class test_getInterestRate {
@Test
void test() {
BankAccount test = new BankAccount();
double rate = test.getInterestRate(1.0); // this SHOULD make rate = 0.5
assertEquals(0.5, rate); //this test fails because rate = 0, not 0.5
}
}
有什么建议吗?这是我第一次使用 JUnit 框架。我阅读/观看的所有教程都使用非常简单的方法,所以我被卡住了。
【问题讨论】:
-
我认为如果您检查 test.type() 的输出,您会发现问题。运行此测试时,您认为您的帐户属于哪种类型?
-
test.getInterestRate(1.0);return 0 所以test()的结果是正确的。 -
为什么一个名为
get的方法会带参数并改变状态?此外,您在没有明确原因的情况下比较整数和双精度数。
标签: java eclipse unit-testing junit