我想要测试以下方法,如果int
条件为真,它只会增加Boolean
:
public void incrementIfConditionMet(Boolean personCheckedIn) {
int peopleInHotel=0;
if (personCheckedIn==true){
peopleInHotel++
}
}
我对Java中的单元测试非常陌生。我怎样unit test
来检查int是否已经增加?
答案 0 :(得分:7)
目前,您无法在方法外访问peopleInHotel
的值,因为它是在内部创建的。如果要访问它,则应执行以下操作:
private int peopleInHotel=0;
public int getPeopleInHotel() {
return peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn){
peopleInHotel++
}
}
现在,在测试课程中,您可以致电getPeopleInHotel();
所以测试用例是:
int initalValue = classInstance.getPeopleInHotel();
classInstance.incrementIfConditionMet(true);
assertEquals(classInstance.getPeopleInHotel(), initalValue +1);
这也可以解决您在运行方法后不保留值的问题。目前,在您当前的代码设置中,在您完成该方法后,您的peopleInHotel
变量将被丢弃。
答案 1 :(得分:1)
int peopleInHotel=0;
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
public int getPeopleInHotel() { //test the returned value after you've incremented
return peopleInHotel;
}
答案 2 :(得分:1)
试试这样:
public class Hotel {
private int peopleInHotel = 0;
//a constructor...
public int getPeopleInHotel() {
return this.peopleInHotel;
}
public void incrementIfConditionMet(Boolean personCheckedIn) {
if (personCheckedIn==true){
peopleInHotel++
}
}
}
在你的单元测试中,你现在可以做类似的事情:
//defining your TestCase
Hotel hotel = new Hotel();
int initValue = hotel.getPepleInHotel();
hotel.incrementIfconditionmet(true);
assertEquals(hotel.getPeopleInHotel(),initValue+1);