主要目标是在加载场景时运行代码,我知道 Initializable 是推荐的解决方案,我一直在使用它,除了我遇到的问题是它不利于集成测试。
我的初始化方法中的逻辑依赖于以前的场景,所以当我只加载这个屏幕时,我得到了一些 NullPointer 异常,因为我期望存在的一些东西不存在。
我无法模拟这些,因为使用 TestFX,initialize 方法在 setup 的第一行运行,FXMLLoader loader = new FXMLLoader(getClass().getResource("test.fxml"));
.
从那里,我可以loader.getController();
访问生成的控制器并模拟某些类字段和东西,但问题是在初始化方法运行之前我不能这样做。这是一个 catch 22 情况,因为要访问控制器javafx.fxml.FXMLLoader
必须运行,但是当它运行时它会自动执行初始化方法,否则我需要模拟部分或生成预期信息。
那么,我有哪些选择?有没有办法在没有 Initializable 的情况下在场景开始时运行代码?
public class GameScreenController implements Initializable {
private AppService appService;
private PlayerService playerService;
private DirectionService directionService;
private RoomDirectionService roomDirectionService;
@FXML
private javafx.scene.control.Button closeButton;
@FXML
private Label goldAmount;
@FXML
private ImageView player;
private final BooleanProperty wPressed = new SimpleBooleanProperty(false);
private final BooleanProperty aPressed = new SimpleBooleanProperty(false);
private final BooleanProperty sPressed = new SimpleBooleanProperty(false);
private final BooleanProperty dPressed = new SimpleBooleanProperty(false);
@Override
public void initialize(URL url, ResourceBundle resourceBundle) {
this.appService = new AppService();
this.directionService = new DirectionService();
this.roomDirectionService = new RoomDirectionService(this.directionService);
this.goldAmount.setText(String.valueOf(this.appService.getPlayerState().getGoldAmount()));
this.playerService = new PlayerService(this.player, this.appService,
this.roomDirectionService);
this.playerService.moveX(this.appService.getPlayerState().getSpawnCoordinates()[0]);
this.playerService.moveY(this.appService.getPlayerState().getSpawnCoordinates()[1]);
...