# 测试优先设计案例分析

#### 测试优先案例

Hunt the Wumpus

   @Test
public void testMove(){
WumpusGame game = new WumpusGame();
game.connect(4, 5, "E");
game.setPlayerRoom(4);
game.east();
assertEquals(5, game.getPlayerRoom());
}

#### 根据书中的测试代码构造出的实现：

//这里使用lombok来简化Getter, Setter和ToString
@Getter
@Setter
@ToString
public class WumpusGame {

private int playerRoom;

private Map<Integer, Map<String, Integer>> map = new HashMap<>();

public void connect(int firstRoom, int anotherRoom, String direction) {
HashMap<String, Integer> directionMap = new HashMap<>();
directionMap.put(direction, anotherRoom);
map.put(firstRoom, directionMap);
}

public void east() {
int roomNumber = map.get(playerRoom).get("E");
this.setPlayerRoom(roomNumber);
}

run测试方法，测试通过。

1. 整个代码就是在一个类中。感觉是个面向过程的。
2. 存储方向的映射，由于需要存储2个房间以及方向的映射关系，是Map内嵌Map的形式。

#### 下面来优化设计：


@Test
public void testMoveObject(){
Room room4 = new Room(4);
//Set connection between Room and Room.
room4.connect(Direction.EAST, 5);

//construct player and set Room.
Player player = new Player();
player.setRoom(room4);
//let the player to move by east direction.
player.move(Direction.EAST);
//Assert the result after the move action.
assertEquals(5, player.getRoom().getNumber());
}
• Player对象
//Player.java
@Getter
@Setter
@ToString
public class Player {

//the room where the player located.
private Room room;

/**
* @param the direction that the player move to.
*
*/
public void move(Direction direction){
Room nextRoom = this.getRoom().getConnectionMap().get(direction);
this.setRoom(nextRoom);
}
}
• Room对象
//Room.java
@Getter
@Setter
@ToString
public class Room {

//room number(id)
private int number;

public Room(int number) {
this.number = number;
}

//the map to store the other room with this room.
private Map<Direction, Room> connectionMap = new HashMap<>();

//create connection between room and room.
public void connect(Direction direction, int anotherRoom) {
Room room2 = new Room(anotherRoom);
connectionMap.put(direction, room2);
}
}
• 枚举类Direction，包括东西南北四个方向。
//Direction.java
public enum Direction {
EAST, WEST, NORTH, SOUTH;
}

©️2019 CSDN 皮肤主题: 编程工作室 设计师: CSDN官方博客