gpt4 book ai didi

java - JUnit 在测试中捕获异常

转载 作者:行者123 更新时间:2023-11-28 20:52:03 25 4
gpt4 key购买 nike

<分区>

这是我的问题:有人向我提供了一个应用程序,我必须编写测试用例才能使用 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());
}
}

}

异常(exception)是:

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;
}

}

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com