单元测试Java中的集合

时间:2015-07-31 18:19:54

标签: java unit-testing testing junit mockito

我有一个单元测试,允许我遍历包含车辆列表的Collection对象。在每次迭代时,我想检查车辆是否是汽车的一个实例。所以我的代码看起来有点像这样:

import javafx.animation.KeyFrame;
import javafx.animation.KeyValue;
import javafx.animation.Timeline;
import javafx.application.Application;
import javafx.beans.property.DoubleProperty;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.geometry.Point2D;
import javafx.scene.Scene;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.Region;
import javafx.stage.Stage;
import javafx.util.Duration;

public class AnimateXAnchor extends Application {

    @Override
    public void start(Stage primaryStage) {
        Region rect = new Region();
        rect.setPrefSize(100,  100);
        rect.setStyle("-fx-background-color: cornflowerblue;");

        rect.setOnMousePressed(e -> {
            double x = e.getX();
            double y = e.getY();
            System.out.printf("Mouse click in local coordinates: [%.1f, %.1f]%n", x, y);

            Point2D clickInParent = rect.localToParent(x, y);
            System.out.printf("Mouse click in parent coordinates: [%.1f, %.1f]%n%n", clickInParent.getX(), clickInParent.getY());

        });

        AnchorPane root = new AnchorPane();
        root.getChildren().add(rect);
        AnchorPane.setTopAnchor(rect, 10.0);

        DoubleProperty x = new SimpleDoubleProperty();
        x.addListener((obs, oldX, newX) -> AnchorPane.setLeftAnchor(rect, newX.doubleValue()));

        Timeline animation = new Timeline(
            new KeyFrame(Duration.ZERO, new KeyValue(x, 0)),
            new KeyFrame(Duration.seconds(5), new KeyValue(x, 400))
        );

        Scene scene = new Scene(root, 600, 600);
        primaryStage.setScene(scene);
        primaryStage.show();
        animation.play();
    }

    public static void main(String[] args) {
        launch(args);
    }
}

所以我写了相应的代码:

public class VehicleChecker {
    protected boolean checkVehicles(Garage garage) {
        for (Vehicle vehicle : garage.getVehicles() {
            if (vehicle instanceof Automobile) return true;
        }
    }
}

验证语句出现问题。根据它的编写方式,测试应该通过。然而,当我单步执行代码时,代码只是完全跳过for循环。这是为什么?迭代通过Collection而不是ArrayList的方式有什么不同吗?如果是这样,我该如何正确模拟这种互动呢?

1 个答案:

答案 0 :(得分:0)

您确定已使用MockitoAnnotations.initMocks初始化了模拟?