我写的实用程序无法正常工作+测试用例



我编写的实用程序无法正常工作。因此,我有两个实用程序可以做不同的事情:

  1. ExtractPhoneNumber-如果电话号码为null,则返回null;如果不是null,则实用程序必须从号码中删除除数字以外的所有字符(例如"+"或"-"或"(("(如果数字以0开头,则我的实用程序写入变量phone,不带0(012345->12345(如果电话号码的长度+国家代码号码(字符数(<或者>超过配置中允许的数字,它将返回null如果该号码不包含国家代码,则将该国家代码添加到电话号码

  2. ValidatePhoneNumber-如果我的字符串与正则表达式匹配,则返回true,如果不匹配,则为false(如果电话号码包含"(("以外的内容(;或"+"或"-"则实用程序应返回false(

我试图解释实用程序应该如何工作,在我写了它们之后,我写的测试不幸没有通过,所以我不明白我的错误是什么,我在它们上放了2个实用程序和测试。

以下是它们的实用程序和测试:

public String extractPhoneNumber(String value) {
String phone = StringUtils.trimToNull(value);
if (phone == null)
return null;
phone = phone.replaceAll("[^0-9]", "");
if (phone.startsWith("0")) {
phone = phone.substring(1);
}
if (phone.length() + configService.getPhoneCountryCode().length() < configService.getPhoneNumberLength()) {
return null;
} else {
if (!phone.startsWith(configService.getPhoneCountryCode())) {
if (phone.length() + configService.getPhoneCountryCode().length() > configService.getPhoneNumberLength()) {
return null;
}
phone = configService.getPhoneCountryCode() + phone;
}
}
return phone;
}

public final static Pattern VALID_PHONE_NUMBER_PATTERN =
Pattern.compile("[^0-9()\-+]");
public boolean validatePhoneNumber(String phoneNumber) {
if (phoneNumber == null) {
return false;
} else {
Matcher matcher = VALID_PHONE_NUMBER_PATTERN.matcher(phoneNumber);
if (matcher.matches()) {
return true;
} else {
return false;
}
}
}

测试:

https://i.stack.imgur.com/RqkMK.jpg

https://i.stack.imgur.com/XJiHR.jpg

您的测试正在对测试中未使用的实例变量使用@Mock@InjectMocks

UtilService上的@InjectMocks本身不是模拟btw,因此不应称为utilsServiceMock,而应简称为utilsService。然后,您需要模拟configService的方法返回值(这是一个模拟(,以返回测试utilsService所需的数据。

UtilsService应该接受configService作为构造函数参数。奇怪的是,您有一个utilsService构造函数,它不接受任何参数;事实并非如此。

最后,您需要在测试中使用实例变量utilsService,而不是每次都重新创建UtilsService对象。至于您的核心逻辑,您应该首先修复测试,然后使用它们来查找代码中的任何错误(如果有的话(。

相关内容

最新更新