我正在为我正在处理的项目编写单元测试,每次运行第二个测试方法时CheckIfRoomTwoHasTheCorrectProperties()我得到一个System.ArgumentNullException。
[TestMethod]
public void CheckIfRoomTwoHasTheCorrectProperties()
{
IDungeonController objectUndertest = new DungeonController();
IRoom secondRoom = objectUndertest.Rooms.FirstOrDefault(y => y.RoomNumber == 2);
Assert.IsNotNull(secondRoom, "Should create room number 2");
Assert.AreEqual(2, secondRoom.Doors.Count);
Assert.AreEqual(1, secondRoom.RoomContents.Count);
Assert.AreEqual("Key", secondRoom.RoomContents[1].Name, "Unexpected object added to room");
IDungeonDoor southWallUnlocked = secondRoom.Doors.FirstOrDefault(
x => x.Location == DoorLocationEnum.South
&& x.Door.IsLocked == false);
Assert.IsNotNull(southWallUnlocked, "Door in south wall is unlocked");
IDungeonDoor eastWallUnlocked = secondRoom.Doors.FirstOrDefault(
x => x.Location == DoorLocationEnum.East
&& x.Door.IsLocked == false);
Assert.IsNotNull(eastWallUnlocked, "Door in south wall is locked");
}
此处的代码抛出异常;
objectUndertest.Rooms.FirstOrDefault(y => y.RoomNumber == 2);
Assert.IsNotNull(secondRoom, "Should create room number 2");
下面第一个房间的测试工作正常
[TestMethod]
public void CheckIfRoomOneHasTheCorrectProperties()
{
IDungeonController ojectUnderTest = new DungeonController();
ojectUnderTest.Initialise();
IRoom firstRoom = ojectUnderTest.Rooms.FirstOrDefault(y => y.RoomNumber == 1);
Assert.IsNotNull(firstRoom, "Should create room number 1");
Assert.AreEqual(3, firstRoom.Doors.Count);
Assert.AreEqual(2, firstRoom.RoomContents.Count);
Assert.AreEqual("Tap", firstRoom.RoomContents[0].Name, "Unexpected object added to room");
IDungeonDoor southWallUnlocked = firstRoom.Doors.FirstOrDefault(
x => x.Door.IsLocked == false
&& x.Location == DoorLocationEnum.South);
Assert.IsNotNull(southWallUnlocked, "Door in south wall should be unlocked");
IDungeonDoor northWallUnlocked = firstRoom.Doors.FirstOrDefault(x =>
x.Door.IsLocked == false
&& x.Location == DoorLocationEnum.North);
Assert.IsNotNull(northWallUnlocked, "Door in north wall should be unlocked");
IDungeonDoor eastWallLoacked = firstRoom.Doors.FirstOrDefault(
x => x.Door.IsLocked == true
&& x.Location == DoorLocationEnum.East);
Assert.IsNotNull(eastWallLoacked, "Door in east wall should be locked");
}
两个测试的代码都是
IRoom room1 = new Room();
room1.RoomNumber = 1;
room1.AddDungeonDoor(new DungeonDoor(new Door(), DoorLocationEnum.South));
room1.AddDungeonDoor(new DungeonDoor(new Door(), DoorLocationEnum.North));
room1.AddDungeonDoor(new DungeonDoor(new Door{IsLocked = true}, DoorLocationEnum.East));
room1.AddRoomObject(new Tap());
Rooms.Add(room1);
IRoom room2 = new Room();
room2.RoomNumber = 2;
room2.AddDungeonDoor(new DungeonDoor(new Door {IsLocked = false }, DoorLocationEnum.South));
room2.AddDungeonDoor(new DungeonDoor(new Door { IsLocked = false}, DoorLocationEnum.East));
room1.AddRoomObject(new Key());
Rooms.Add(room2);
答案 0 :(得分:1)
正如@Reg Edit在评论中建议的那样,测试CheckIfRoomTwoHasTheCorrectProperties
在安排步骤中错过了对ojectUnderTest.Initialise();
的调用。