0
我正在尝试测试我的Play应用程序控制器,但我正在努力寻找让测试在使用控制器实例的同时返回两个会话数据。使用会话和控制器实例测试POST请求。
public class HomeControllerTest extends WithApplication {
@Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.configure("play.http.router", "router.Routes")
.build();
}
@Test
public void testGameChoiceHvH() {
Map form = new HashMap<String, String>();
form.put("gameType", "0");
HomeController homeController = new HomeController();
Result result = invokeWithContext(fakeRequest().bodyForm(form),
() -> homeController.chooseGame());
assertEquals(SEE_OTHER, result.status());
assertEquals("/play", result.header("Location").get());
assertFalse(result.session().isEmpty());
String gameId = result.session().get("game_id");
assertTrue(homeController.getGame(gameId).getCurrentPlayer() instanceof Human);
}
}
这里的最后断言模拟采取存储在会话中的游戏ID,并用它获取游戏实例,在控制器动作创建并存储在控制器实例中的地图。问题是,通过使用invokeWithContext,result
完全不包含Cookie对象,因此无法检索。
另一种方法我发现创建一个POST请求如下:
public class HomeControllerTest extends WithApplication {
@Override
protected Application provideApplication() {
return new GuiceApplicationBuilder()
.configure("play.http.router", "router.Routes")
.build();
}
@Test
public void testGameChoiceHvH() {
Map form = new HashMap<String, String>();
form.put("gameType", "0");
HomeController homeController = new HomeController();
Result result = route(fakeRequest(routes.HomeController.chooseGame()).bodyForm(form));
assertEquals(SEE_OTHER, result.status());
assertEquals("/play", result.header("Location").get());
assertFalse(result.session().isEmpty());
String gameId = result.session().get("game_id");
assertTrue(homeController.getGame(gameId).getCurrentPlayer() instanceof Human);
}
}
然而,这显然意味着,最终的断言看的HomeController的新实例,而不是一个使用因此,Map是空的。
为了清楚起见,这里是有关控制器代码:
public class HomeController extends Controller {
private WebInterface ui = new WebInterface();
private Map<String, Board> boardMap = new HashMap<>();
private Map<String, Game> gameMap = new HashMap<>();
public Game getGame(String gameId) {
return gameMap.get(gameId);
}
public Result chooseGame() {
Map<String, String[]> request = request().body().asFormUrlEncoded();
Board board = new Board();
Game game = new Game(new PlayerFactory(ui).create(GameType.values()[Integer.valueOf(request.get("gameType")[0])]));
boardMap.put(Integer.toString(board.hashCode()), board);
gameMap.put(Integer.toString(game.hashCode()), game);
session("game_id", Integer.toString(game.hashCode()));
session("board_id", Integer.toString(board.hashCode()));
return redirect("/play");
}
任何帮助将非常感激。