因此,我正在Eclipse中使用JUnit测试用例,我的构造函数出现错误,显示“默认构造函数无法处理由隐式超构造函数引发的异常类型InvalidArgException。必须定义显式构造函数”。
我会把我目前掌握的一切都包括在内,但是我被困在这里,不知道现在该怎么办。任何帮助都将不胜感激!!
这是测试类
package test;
import static org.junit.jupiter.api.Assertions.*;
import org.junit.jupiter.api.Test;
import Main.Contact;
class ContactTest {
Contact contact = new Contact("13579", "Garrett", "Strang", "1234567890", "2468 Washington Avenue");
@Test
void getContactID() {
assertEquals("13579", contact.getContactID());
}
@Test
void getFirstname() {
assertEquals("Garrett", contact.getFirstName());
}
@Test
void getLastName() {
assertEquals("Strang", contact.getLastName());
}
@Test
void getPhoneNumber() {
assertEquals("1234567890", contact.getPhoneNumber());
}
@Test
void getAddress() {
assertEquals("2468 Washington Avenue", contact.getAddress());
}
}
联系人类:
public class Contact {
//declare private contact objects
private String contactID;
private String firstName;
private String lastName;
private String phoneNum;
private String address;
//Ensure invalid objects are caught
public Contact(String cID, String fN, String lN, String pN, String addr) throws InvalidArgException {
//contact ID string cannot be longer than 10 characters. The contact ID shall not be null and shall not be updatable.
if (cID == null || cID.length() > 10) {
throw new InvalidArgException("CONTACT ID IS INVALID");
}
if (fN == null || fN.length() > 10) {
throw new InvalidArgException("FIRST NAME IS INVALID");
}
if (lN == null || lN.length() > 10) {
throw new InvalidArgException("LAST NAME IS INVALID");
}
if (pN == null || pN.length() > 10) {
throw new InvalidArgException("PHONE NUMBER IS INVALID");
}
if (addr == null || addr.length() > 10) {
throw new InvalidArgException("ADDRESS IS INVALID");
}
}
InvalidArgExcetion类别:
package Main;
@SuppressWarnings("serial")
public class InvalidArgException extends Exception {
public InvalidArgException(String string) {
super(string);
System.out.println(string + "IS AN INVALID ARGUMENT");
}
}
1条答案
按热度按时间nwlls2ji1#
Contact
的构造可能会引发已检查异常InvalidArgException
。因为
ContactTest
的构造涉及到创建一个Contact
示例,所以它也可能抛出一个InvalidArgException
,但是ContactTest
并没有声明这个。您需要向
ContactTest
添加一个构造函数:(我不知道为什么你的例子引用了超级构造函数。在我的JDK中,我只得到了
java: unreported exception java.lang.Exception; must be caught or declared to be thrown
)