Junit toString部分覆盖

时间:2015-03-05 18:29:35

标签: java junit tostring

我正在网络中对字符串类进行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());
        } 
    }

有人可以向我解释为什么这仍然被视为部分报道?

1 个答案:

答案 0 :(得分:2)

你的toString方法正在考虑一个快乐的场景,你的某些方法不会抛出异常,因此它永远不会进入catch块。

您应该尝试以这样的方式调用该方法,以便进入catch块,您可以在其中返回异常的消息。