Java JUnit写作测试
我目前正在学习如何使用JUnit为Java代码编写测试 测试设置和测试语法是否正常?我应该在同一个测试类中保留一个类的所有测试方法吗 希望有人能给一些反馈Java JUnit写作测试,java,testing,junit,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", 20
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!");
}
static HashMap hotelRooms=new HashMap();
public int registeroom(int numberOfPeople、String roomtype、int price){
//检查非法输入
如果(人数>10){
抛出新的IllegalArgumentException(“错误!人员太多!”);
}
如果(roomtype==“低价房”){
Lowpriceroom newRoom=新的Lowpriceroom(人数,价格);
hotelRooms.put(newRoom.getID(),newRoom);
return newRoom.getID();
}
else if(roomtype==“qualityroom”){
Qualityroom newRoom=新Qualityroom(人数、价格);
hotelRooms.put(newRoom.getID(),newRoom);
return newRoom.getID();
}
否则{
抛出新的IllegalArgumentException(“错误!无效的roomtype!”);
}
一切看起来都不错。尽管你永远不应该使用==
测试字符串相等性。请改用.equals()
来测试。我投票将这个问题作为离题题题来结束,因为要求查看“real”老实说,代码应该是这样的,我不同意这里的@killjoy。在您的设置方法中进行这么多设置不是一个好主意。相反,每个测试用例都应该自己进行相关的设置。例如,您可能会问,您是否应该在一个测试中使用3个断言。@GhostCat我应该在每个测试用例中编写相关的设置,而不是嗯?我还应该对一些声明使用setUp()和tearDown()方法吗?@GhostCat谢谢你的回答,现在变得更清楚了!:)