这是我的问题:我已经提供了一个应用程序,并且必须编写测试用例才能使用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