我无法弄清楚如何为我的程序中的测试程序部分编写代码。 我提供了我制作的Battery类,但需要帮助让测试人员运行所有内容。
package batterytester;
public class Battery {
// identifies variables and cap means capacity
double fullCharge = 2500;
double batteryCap;
Battery() {
fullCharge = 2500;
}
public Battery(double cap) {
batteryCap = cap;
fullCharge = cap;
}
void charge() {
batteryCap = fullCharge;
}
void drain(double amount) {
batteryCap = batteryCap - amount;
}
double getRemainingCapacity() {
return batteryCap;
}
}
答案 0 :(得分:0)
你看过tutorials on Junit了吗?使用Assert
单元测试方法中使用的简单@Test
语句,您的代码非常容易测试。以下是一些示例:
@Test
public void testChargeOrDrain() { // poor form to have multiple assertions but you get the idea...
Battery battery = new Battery();
assertNotNull("Expected a new battery object", battery);
assertEquals("Expected a full charge of 2500", 2500, battery.getRemainingCapacity();
battery.drain(500);
assertEquals("Expected a partial charge of 500", 500, battery.getRemainingCapacity();
battery.charge();
assertEquals("Expected a full charge of 2500", 2500, battery.getRemainingCapacity();
}
彻底的单元测试将有助于排除错误和异常,并验证代码的每个功能部分是否按预期工作。例如,如果我提供负值,您drain()
函数会发生什么? :)