【问题标题】:Testing a FXGL game测试 FXGL 游戏
【发布时间】:2020-12-22 13:55:39
【问题描述】:

我正在用 Java FXGL 编写一个简单的游戏。我对 Java FX 和 FXGL 非常陌生。

我想用 JUnit5 测试我的游戏,但我无法让它工作...... 问题:当我启动测试时,FXGL 属性尚未初始化。

如果有人能给我一个想法,我会很高兴,如何使用FXGL.getWorldProperties()为班级女巫发起测试

我的班级:

public class Player {

    private int playerColumn = 2;   // The actual column from the player
    private int nColumns;     // Numbers of Columns in the game // Will be set on the init of the game

    public int getPlayerColumn() {
        return playerColumn;
    }

    // Some more code ...

    /**
     * The Input Handler for moving the Player to the right
     */
    public void moveRight() {
        if (playerColumn < nColumns - 1) {
            playerColumn++;
        }
        updatePlayerPosition();
    }


    /**
     * Calculates the x Offset for the Player from the column
     */
    private void updatePlayerPosition() {
        getWorldProperties().setValue("playerX", calcXOffset(playerColumn, playerFactory.getWidth()));
    }

    // Some more code ...

}

我的测试班:我不知道我该怎么做...

@ExtendWith(RunWithFX.class)
public class PlayerTest{

  private final GameArea gameArea = new GameArea(800, 900, 560, 90);
  private final int nColumns = 4; // Numbers of Columns in the game


  @BeforeAll
  public static void init(){
    Main.main(null);
  }

  @Test
  public void playerColumn_init(){
    Player player = new Player();
    assertEquals(2, player.getPlayerColumn());
  }

  @Test
  public void moveLeft_2to1(){
    Player player = new Player();
    player.moveLeft();
    assertEquals(1, player.getPlayerColumn());
  }
}

在这种情况下,测试根本不会启动,因为程序被困在游戏循环中...... 但是,如果我让Main.main(null); - 调用,则探针不会初始化

【问题讨论】:

    标签: java junit5 fxgl


    【解决方案1】:

    通常,您有两种选择:

    1. 这是推荐的方法,因为我假设您想对自己的代码进行单元测试。 FXGL.getWorldProperties() 返回 PropertyMap。你可以让你的Player 类依赖PropertyMap 而不是对FXGL.getWorldProperties() 的内部依赖。例如:
    class Player {
        private PropertyMap map;
    
        public Player(PropertyMap map) {
            this.map = map;
        }
    }
    
    // production code
    var player = new Player(FXGL.getWorldProperties());
    
    // test code
    var player = new Player(new PropertyMap());
    
    1. 不建议这样做,尽管它可以用作集成测试。在不同的线程中使用GameApplication.launch(YourApp.class) 启动整个游戏(它将阻塞直到游戏结束)。然后使用@Test 正常测试您的游戏。

    【讨论】:

    • 不要忘记对 FXGL.GameWorld 做同样的事情 - 如果你在课堂上使用它,那将是 proberty :)
    猜你喜欢
    • 1970-01-01
    • 2010-09-06
    • 2017-01-26
    • 1970-01-01
    • 2021-04-14
    • 2014-11-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多