这是我的问题:我已经提供了一个应用程序,我必须编写测试用例才能使用JUnit对其进行测试。例如:实例化具有属性String name
的对象,此字段不能超过10个字符。我如何将其纳入测试方法?这是我的代码:
要测试的课程是:
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;
}
}
答案 0 :(得分:0)
您的问题是原始构造函数。您在签名中有throws子句。你不应该在构造函数中有一个try / catch块。删除它。
public AquiferPublicData (String name, float current) throws HydricDSSException{
if(name.length()>10) throw new HydricDSSException("Name longer than 10");
myName = name;
currentHeight = current;
}
你应该编写一个JUnit测试,证明如果名称长于10,则抛出异常。
public class AquiferPublicDataTest {
@Test
public void testConstructor_Success() {
// setup
String name = "Jones";
// exercise
AquiferPublicData data = new AquiferPublicData(name, 0.0);
// assert
Assert.assertEquals(name, data.getMyName());
}
@Test(expects = HydricDSSException.class)
public void testConstructor_NameTooLong() throws HydricDSSException {
// setup
String name = "this one is too long";
// exercise
new AquiferPublicData(name, 0.0);
}
}
如果名称为空,您期望什么?这是允许的吗?你现在要获得一个空指针异常。