這是我的問題:我已經提供了一個應用程序,並且必須編寫測試用例才能使用JUnit進行測試。例如:使用屬性String name
實例化對象,並且此字段不能長於10個字符。我如何將其納入測試方法?這裏是我的代碼: 要測試的類是:JUnit在測試中捕獲異常
package hdss.io;
import hdss.exceptions.HydricDSSException;
public class AquiferPublicData implements WaterResourceTypePublicData {
private String myName;
private float currentHeight;
public AquiferPublicData (String name, float current) throws HydricDSSException{
try {
if(name.length()>10) //name must be shorter than 11 chars
throw new HydricDSSException("Name longer than 10");
else{
myName = name;
currentHeight = current;
}
} catch (HydricDSSException e) {
}
}
public String getMyName() {
return myName;
}
}
我的測試方法是:
package hdss.tests;
import static org.junit.Assert.*;
import org.junit.Test;
import hdss.exceptions.HydricDSSException;
import hdss.io.AquiferPublicData;
public class AquiferPublicDataTest {
@Test
public void testAquiferPublicData() {
String notValidName = "this-name-is-too-long";
try {
AquiferPublicData apd = new AquiferPublicData(notValidName, 10);
fail("Was supposed to throw Exception if name is longer than 10 chars");
} catch (HydricDSSException e) {
assertEquals("Name longer than 10", e.getMessage());
}
}
}
,異常是:
package hdss.exceptions;
public class HydricDSSException extends Exception{
/**
*
*/
private static final long serialVersionUID = 1L;
String message;
//Esfuerzo Actual: 1.5 minutos
public HydricDSSException (String message){
this.message = message;
}
//Esfuerzo Actual: 1.5 minutos
public String getMessage(){
return this.message;
}
}
在您發佈問題之前,請確保您已完成基本的谷歌搜索 – Mritunjay
使用並嘗試實施建議的解決方案,但未完成。 Ijust不知道該怎麼辦 – bogALT
提示:在你的代碼中,空的catch catch塊(catch(HydricDSSException e){}')在測試中......究竟是應該做什麼的?我的意思是:除了在你的拋出列表中聲明要拋出的錯誤之外,還要默默地**掉**。換句話說:你的第一個bug已經在那裏了。除此之外:空的抓塊很少是一個好主意! – GhostCat