如何在JAVA中编写一个10位电话号码的Junit测试

nwnhqdif  于 2023-10-20  发布在  Java
关注(0)|答案(1)|浏览(93)

我正在尝试编写一个电话号码的测试用例,其中只允许数字通过。如何在java中使用对象类型来编写它。
我在硬编码字符的地方尝试了这个方法。但我想要一个比这更好的解决方案

TelephoneNumber ExtensionNUM = new TelephoneNumber();
ExtensionNUM.setExtensionNum("!@#$%^&*()_-+=}]{[|;:'<,>./?qwertyuioplkjhgfdsazxcvbnmàrèhìp\òtù");
contactPreference.setTelephoneNumber(ExtensionNUM);
6ovsh4lw

6ovsh4lw1#

因为你是在一个对象中捕获的,你可以简单地在对象的构造函数中Assert这个事实:

public USTelephoneNumber implement TelephoneNumber {
   public USTelephoneNumber(String number) {
    // here you can handle +1 formats
    // But of course Canada also uses +1, so +1 is just a sanity check
    // but you can also apply much more sophisticated logic (like length, or using external validation.
     if (!number.startsWith("+1")){
        throw new IllegalArgumentException(String.format("%s is not a US number", number));
     }
     
     if (!number.replaceAll("[ ]","").replaceAll("+1","").matches("[0-9]+")) {
        throw new IllegalArgumentException(String.format("%s is not all numbers",number));

   }
}
@Throws(IllegalArgumentException.class)
public testIsNotUsPhoneNumber() throws IllegalArgumentException {
    new USPhoneNumber("+48 158 610 715");
}

public testIsUsPhoneNumber() {
    new USPhoneNumber("+1 425 388 2588");
}

相关问题