mercredi 25 mars 2020

Unittest using spock - test interaction on private fields

I want to test the addMCUand removeMCUmethods of my MCUModelclass using Spock. However, I am a bit puzzled on how to approach this.

public class MCUModel {

    private static int counter = 1;

    private final ObjectProperty<MCU> selectedMCU;
    private final ObservableList<MCU> mcuList;

    public MCUModel() {
        selectedMCU = new SimpleObjectProperty<>(null);
        mcuList = FXCollections.observableArrayList();
    }

    public ObjectProperty<MCU> selectedMCUProperty() {
        return selectedMCU;
    }

    public void setSelectedMCU(MCU mcu) {
        selectedMCU.set(mcu);
    }

    public ObservableList<MCU> getMCUList() {
        return mcuList;
    }

    public void addMCU() {
        MCU mcu = new MCU();
        mcu.setName("MCU" + counter++);
        mcuList.add(mcu);
        selectedMCU.set(mcu);
    }

    public void removeMCU() {
        if (selectedMCU.get() == null) return;

        int index = mcuList.indexOf(selectedMCU.get());
        mcuList.remove(index);

        if (mcuList.size() == 0)
            selectedMCU.set(null);
        else if (mcuList.size() > index)
            selectedMCU.set(mcuList.get(index));
        else
            selectedMCU.set(mcuList.get(--index));
    }

}

In other examples on here the suggestion was made to change the constructor along the lines of:

public MCUModel(ObjectProperty<MCU> selectedMCU, ObservableList<MCU> mcuList) {
        this.selectedMCU = selectedMCU;
        this.mcuList = mcuList;
    }

This would allow me to mock the fields in order to test whether there methods are called or not. However, I am not sure that this is the right approach in this particular case.

I would guess that, in case of the addMCU method, that I want to test whether or not an new instance is created, and that both mcuList.add(mcu) and selectedMCU.set() are called and passed this instance.

Aucun commentaire:

Enregistrer un commentaire