我正在为网络bean中的字符串类创建一个junit测试论坛:
public String toString() {
try {
return "I am ContainerTruck " + getIdentifier() + ".\n\tI am at "
+ getLocation() + " and am heading to " + getDestination()
+ ".\n\tMy load is " + getCurrentLoadWeight() + " and my max load is "
+ getMaxLoadWeight() + ".\n\tDistance to my destination is "
+ String.format("%4.2f", distance(getDestination())) + ". "
+ (atDestination() ? "I am there!" : "I'm not there yet");
} catch (InvalidDataException ex) {
return ex.getMessage();
}
}
Netbeans一直说我的测试得到了部分覆盖:
public void testToString(){
double lX = 1.0;
double lY = 1.0;
double lZ = 1.0;
double dX = 1.0;
double dY = 1.0;
double dZ = 1.0;
double spd = 1.0;
double mxSpd = 1.0;
double mlw = 1.0;
try{
ContainerTruck result = new ContainerTruck(lX, lY, lZ, dX, dY, dZ, spd, mxSpd, mlw);
IdentifiableImpl imp = new IdentifiableImpl(result.getIdentifier());
assertNotNull(result);
assertEquals("I am ContainerTruck " + imp.getIdentifier() + ".\n\tI am at [1.00, 1.00, 1.00] and am heading to [1.00, 1.00, 1.00].\n\tMy load is 0.0 and my max load is 1.0.\n\tDistance to my destination is 0.00. I am there!", result.toString());
assertEquals(imp.getIdentifier(),result.getIdentifier());
assertEquals(0.0, result.getCurrentLoadWeight(), delta);
assertEquals(1.0, result.getLocationZ(), delta);
assertEquals(1.0, result.getLocationY(), delta);
assertEquals(1.0, result.getLocationX(), delta);
assertEquals(1.0, result.getMaxLoadWeight(), delta);
assertEquals(1.0, result.getDestinationX(), delta);
assertEquals(true, result.atDestination());
assertEquals(1.0, result.getDestinationY(), delta);
assertEquals(1.0, result.getDestinationZ(), delta);
assertEquals(1.0, result.getSpeed(), delta);
assertEquals(1.0, result.getMaxSpeed(), delta);
}catch (InvalidDataException ex) {
fail(ex.getMessage());
}
}
有人可以向我解释为什么这仍然被认为是部分覆盖吗?
最佳答案
您的toString方法考虑的只是一个快乐的场景,其中某些方法不会引发异常,因此它永远不会进入catch块。
您应该尝试以某种方式调用该方法,以使您进入catch块,在其中可以返回异常的消息。