JUnit-编写测试

时间:2018-08-24 13:40:00

标签: java testing junit

我目前正在学习如何使用JUnit对Java代码编写测试。

测试的设置和该测试的语法可以吗?我应该将一个类的所有测试方法都保留在同一测试类中吗?

希望有人可以提供反馈!

public class HotelTest {

Hotel hotel;
int id1=0; 
int id2=0;

@Before
public void setUp(){
    hotel = new Hotel();
    this.id1 = hotel.registerRoom(5, "lowpriceroom", 200);
    this.id2 = hotel.registerRoom(3, "qualityroom", 300);

}
@After
public void tearDown(){
    hotel.hotelRooms.clear();

}

@Test
public void testRegisterRoom() {
    System.out.println(hotel.hotelRooms);
    assertTrue(hotel.hotelRooms.size() == 2);
    assertEquals(200, hotel.hotelRooms.get(id1).getPrice());
    assertEquals(3, hotel.hotelRooms.get(id2).getNumberOfPeople()); 

}

@Test(expected = IllegalArgumentException.class)
public void testExceptionWrongRoom() {
    hotel.registerRoom(3, "wrongRoom", 200);
}
@Test(expected = IllegalArgumentException.class)
public void testExceptionTooManyPeople() {
    hotel.registerRoom(11, "lowpriceroom", 200);
}

这是我正在测试的方法:

    static HashMap<Integer, Room> hotelRooms = new HashMap<Integer, Room>();


        public int registerRoom(int numberOfPeople, String roomtype, int price){
                //Checking for illegal input
                if(numberOfPeople > 10){
                    throw new IllegalArgumentException("Error! Too many persons!"); 
                }
                if(roomtype == "lowpriceroom" ){
                    Lowpriceroom newRoom = new Lowpriceroom(numberOfPeople, price);
                    hotelRooms.put(newRoom.getID(), newRoom);
                    return newRoom.getID();
                }
                else if(roomtype == "qualityroom" ){
                    Qualityroom newRoom = new Qualityroom(numberOfPeople, price);
                    hotelRooms.put(newRoom.getID(), newRoom);
                    return newRoom.getID();
                }
                else{
                    throw new IllegalArgumentException("Error! Not valid roomtype!");

               }

0 个答案:

没有答案