首页 > 其他分享 >IpAdressServiceImpl的测试

IpAdressServiceImpl的测试

时间:2024-11-15 10:33:49浏览次数:1  
标签:String errCode response 测试 IpAdressServiceImpl new public errMsg

import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.junit.jupiter.api.BeforeEach;
import org.junit.jupiter.api.Test;
import org.mockito.InjectMocks;
import org.mockito.Mock;
import org.mockito.MockitoAnnotations;

import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CountDownLatch;

import static org.junit.jupiter.api.Assertions.;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.
;

@Slf4j
class IpAddressServiceImplTest {

@Mock
private IpCheckService ipCheckService;

@InjectMocks
private IpAddressServiceImpl ipAddressService;

@BeforeEach
void setUp() {
    MockitoAnnotations.openMocks(this);
}

@Test
void testAllIpAddressCheck_Success() throws InterruptedException {
    // Arrange
    AllIpAddressCheckRequest request = new AllIpAddressCheckRequest();
    List<String> ipAddressList = Collections.singletonList("192.168.1.1");
    request.setIpAddressList(ipAddressList);

    Map<String, Boolean> map = new ConcurrentHashMap<>();
    CountDownLatch latch = new CountDownLatch(1);

    doNothing().when(ipCheckService).asyncIpCheck(anyString(), anyMap(), eq(latch));

    // Act
    AllIpAddressCheckResponse response = ipAddressService.alllpAddressCheck(request);

    // Assert
    assertTrue(response.isSuccess());
    assertNotNull(response.getMap());
    assertEquals(1, response.getMap().size());
    assertTrue(response.getMap().get("192.168.1.1"));
}

@Test
void testAllIpAddressCheck_EmptyIpAddressList() {
    // Arrange
    AllIpAddressCheckRequest request = new AllIpAddressCheckRequest();
    request.setIpAddressList(Collections.emptyList());

    // Act & Assert
    Exception exception = assertThrows(TitanException.class, () -> {
        ipAddressService.alllpAddressCheck(request);
    });

    // Assert
    assertEquals("所传参数为空!", exception.getMessage());
}

@Test
void testAllIpAddressCheck_NullIpAddressList() {
    // Arrange
    AllIpAddressCheckRequest request = new AllIpAddressCheckRequest();
    request.setIpAddressList(null);

    // Act & Assert
    Exception exception = assertThrows(TitanException.class, () -> {
        ipAddressService.alllpAddressCheck(request);
    });

    // Assert
    assertEquals("所传参数为空!", exception.getMessage());
}

@Test
void testAllIpAddressCheck_InvalidIpAddressFormat() {
    // Arrange
    AllIpAddressCheckRequest request = new AllIpAddressCheckRequest();
    List<String> ipAddressList = Collections.singletonList("invalid_ip");
    request.setIpAddressList(ipAddressList);

    // Act & Assert
    Exception exception = assertThrows(TitanException.class, () -> {
        ipAddressService.alllpAddressCheck(request);
    });

    // Assert
    assertEquals("所传 ip 地址格式错误", exception.getMessage());
}

@Test
void testAllIpAddressCheck_IpCheckFailure() throws InterruptedException {
    // Arrange
    AllIpAddressCheckRequest request = new AllIpAddressCheckRequest();
    List<String> ipAddressList = Collections.singletonList("192.168.1.1");
    request.setIpAddressList(ipAddressList);

    Map<String, Boolean> map = new ConcurrentHashMap<>();
    CountDownLatch latch = new CountDownLatch(1);

    doThrow(new TitanException("IP校验异常")).when(ipCheckService).asyncIpCheck(anyString(), anyMap(), eq(latch));

    // Act & Assert
    Exception exception = assertThrows(TitanException.class, () -> {
        ipAddressService.alllpAddressCheck(request);
    });

    // Assert
    assertEquals("IP校验异常", exception.getMessage());
}

}

// 辅助类和枚举类的假定实现

class AllIpAddressCheckRequest {
private List ipAddressList;

public List<String> getIpAddressList() {
    return ipAddressList;
}

public void setIpAddressList(List<String> ipAddressList) {
    this.ipAddressList = ipAddressList;
}

}

class AllIpAddressCheckResponse extends BaseResponse {
private HashMap<String, Boolean> map;

public HashMap<String, Boolean> getMap() {
    return map;
}

public void setMap(HashMap<String, Boolean> map) {
    this.map = map;
}

}

abstract class BaseResponse {
private boolean success;
private String errCode;
private String errMsg;

public boolean isSuccess() {
    return success;
}

public void setSuccess() {
    this.success = true;
}

public String getErrCode() {
    return errCode;
}

public void setErrCode(String errCode) {
    this.errCode = errCode;
}

public String getErrMsg() {
    return errMsg;
}

public void setErrMsg(String errMsg) {
    this.errMsg = errMsg;
}

}

class RespUtils {
private static final Logger log = LoggerFactory.getLogger(RespUtils.class);

private RespUtils() {}

public static void setSuccess(BaseResponse response) {
    response.setSuccess();
}

public static void setError(Exception e, ErrCodeBaseEnum errCode, BaseResponse response) {
    if (e instanceof BaseBizException) {
        BaseBizException exception = (BaseBizException) e;
        response.setErrCode(exception.getErrCode());
        response.setErrMsg(exception.getErrMsg());
    } else if (errCode != null) {
        response.setErrCode(errCode.getErrCode());
        response.setErrMsg(errCode.getErrMsg());
    } else {
        log.error("errCode为空, 设置默认错误");
        response.setErrCode(HadesErrCodeEnum.BIZ_UNKNOWN_ERROR.getErrCode());
        response.setErrMsg(HadesErrCodeEnum.BIZ_UNKNOWN_ERROR.getErrMsg());
    }
}

public static void setError(ErrCodeBaseEnum errCode, BaseResponse response) {
    setError((Exception) null, errCode, response);
}

public static Object newReturn(Class<?> returnType, String errCode, String errMsg) {
    if (returnType == null) {
        return null;
    } else {
        Object ret = null;
        try {
            ret = returnType.newInstance();
            if (ret instanceof BaseResponse) {
                BaseResponse response = (BaseResponse) ret;
                response.setErrCode(errCode);
                response.setErrMsg(errMsg);
                ret = response;
            }
        } catch (IllegalAccessException | InstantiationException var5) {
            log.info((String) null, var5);
        }
        return ret;
    }
}

public static Object newReturn(Class<?> returnType, BaseBizException e) {
    return newReturn(returnType, e.getErrCode(), e.getErrMsg());
}

public static Object newReturn(Class<?> returnType, ErrCodeBaseEnum errCodeBaseEnum) {
    return newReturn(returnType, errCodeBaseEnum.getErrCode(), errCodeBaseEnum.getErrMsg());
}

}

class TitanException extends RuntimeException {
public TitanException() {
super();
}

public TitanException(String message) {
    super(message);
}

public TitanException(String message, Throwable cause) {
    super(message, cause);
}

public TitanException(Throwable cause) {
    super(cause);
}

}

class IpCheckService {
@Async(value = "asyncIpCheckExecutor")
public void asyncIpCheck(String ipAddress, Map<String, Boolean> map, CountDownLatch latch) {
try {
InetAddress address = InetAddress.getByName(ipAddress);
map.put(ipAddress, true);
if (address.isReachable(3000)) {
map.put(ipAddress, false);
}
} catch (Exception e) {
log.error("IP校验异常", e);
throw new TitanException("IP校验异常", e);
} finally {
latch.countDown();
}
}
}

interface ErrCodeBaseEnum {
String getErrCode();

String getErrMsg();

}

enum HadesErrCodeEnum implements ErrCodeBaseEnum {
BIZ_UNKNOWN_ERROR("UNKNOWN_ERROR", "未知错误");

private final String errCode;
private final String errMsg;

HadesErrCodeEnum(String errCode, String errMsg) {
    this.errCode = errCode;
    this.errMsg = errMsg;
}

@Override
public String getErrCode() {
    return errCode;
}

@Override
public String getErrMsg() {
    return errMsg;
}

}

class BaseBizException extends RuntimeException {
private String errCode;
private String errMsg;

public BaseBizException(String errCode, String errMsg) {
    super(errMsg);
    this.errCode = errCode;
    this.errMsg = errMsg;
}

public String getErrCode() {
    return errCode;
}

public String getErrMsg() {
    return errMsg;
}

}

@Service("ipAddressService")
class IpAddressServiceImpl implements IpAddressService {
@Autowired
private IpCheckService ipCheckService;

@Override
public AllIpAddressCheckResponse alllpAddressCheck(AllIpAddressCheckRequest request) {
    AllIpAddressCheckResponse response = new AllIpAddressCheckResponse();
    Map<String, Boolean> map = new ConcurrentHashMap<>();
    List<String> ipAddressList = request.getIpAddressList();
    response.setResult(true);
    if (ipAddressList == null || ipAddressList.isEmpty()) {
        throw new TitanException("所传参数为空!");
    }
    Set<String> ipAddressSet = new HashSet<>(ipAddressList);
    CountDownLatch latch = new CountDownLatch(ipAddressSet.size());
    try {
        for (String ipAddress : ipAddressSet) {
            if (ipAddress == null || ipAddress.isEmpty()) {
                throw new TitanException("所传 ip地址为空");
            }
            if (!ipAddressCheck(ipAddress)) {
                throw new TitanException("所传 ip 地址格式错误");
            }
            ipCheckService.asyncIpCheck(ipAddress, map, latch);
        }
        latch.await();
        map.keySet().forEach(key -> {
            if (!map.get(key)) {
                response.setResult(false);
            }
        });
        HashMap<String, Boolean> hashMap = Maps.newHashMap(map);
        response.setMap(hashMap);
        RespUtils.setSuccess(response);
    } catch (InterruptedException e) {
        log.error("IP检验线程数据同步异常", e);
        throw new TitanException("IP检验线程数据同步异常", e);
    } catch (Exception e) {
        log.error("IP检验异常", e);
        throw new TitanException("IP检验异常", e);
    }
    return response;
}

private static boolean ipAddressCheck(String ipAddress) {
    return ipAddress.matches("^(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[1-9])\\. "
            + "((1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])\\.){2}"
            + "(1\\d{2}|2[0-4]\\d|25[0-5]|[1-9]\\d|[0-9])$");
}

}

标签:String,errCode,response,测试,IpAdressServiceImpl,new,public,errMsg
From: https://www.cnblogs.com/lmzzr24/p/18547494

相关文章

  • SpringCloud2023实战之接口服务测试工具SpringBootTest
    你好,这里是专栏“SpringCloud2023实战”。点击查看专栏SpringCloud实战往期推荐:SpringCloud和SpringBoot的版本依赖该怎么选择SpringCloud2023最新版本该如何进行组件选型?如何简洁高效的搭建一个SpringCloud2023的maven工程如何在SpringCloud2023中快速集成注册中心如何在......
  • 充电桩测试的主要内容有哪些?
    充电桩测试是确保充电桩安全、高效运行的关键环节。充电桩测试的主要内容包括以下几个方面:电气性能测试:电气性能测试主要包括输入输出电压、电流、功率因数等参数的测量,以及充电桩与电动汽车之间的通信功能测试。这些测试旨在确保充电桩能够为电动汽车提供稳定、可靠的充电服务......
  • 自动化测试环境配置-selenium库和谷歌浏览器版(离线安装)
    环境下载链接:https://pan.baidu.com/s/1acJJrA087zf_e02at3hoUg?pwd=f83d提取码:f83d 第一步,取消谷歌浏览器的自动升级 再去控制面板卸载原来的谷歌浏览器 第二步,安装谷歌浏览器80版本 通过设置查看版本号,该版本是不会自动升级的 第三步:直接使用下载好的驱动......
  • 软件测试笔记|Python自动化测试|python中的数值运算有何特点?
    一、类型方面特点1.类型丰富:支持整数(int)、浮点数(float)、复数(complex)等多种数值类型。2.动态类型:声明变量时无需指定类型,运行时确定类型。二、精度相关特点1.整数精度:整数类型不会溢出,可处理任意大小整数,受机器内存限制。2.浮点数精度:通常用双精度浮点数表示,符合IEEE7......
  • 软件测试笔记|Python自动化测试|isinstance与type有什么区别,分别有什么特点?
    一、区别isinstance和type都可用于判断对象的类型,但它们有明显区别:1.判断方式•type:直接返回对象的类型,是通过比较对象的类型是否完全相同来判断,更关注对象确切的类型本身。•isinstance:判断一个对象是否是指定类型(或其派生类型)的实例,考虑了继承关系,更灵活些。2.对继......
  • GB 9706.1-2020医疗器械安规测试项目有哪些?
    医疗器械安规测试项目包括以下几项:1、结构检查与测试:测试设备的结构是否符合标准要求,包括各个部件的连接、固定、防护等。2、电源电压适应性:测试设备在规定范围内的电源电压下是否能正常工作。3、绝缘电阻:测试设备的绝缘材料电阻值是否符合标准要求,以避免电流泄漏和电击......
  • #渗透测试#SRC漏洞挖掘#蓝队基础之网络七层杀伤链04 终章
    网络杀伤链模型(KillChainModel)是一种用于描述和分析网络攻击各个阶段的框架。这个模型最初由洛克希德·马丁公司提出,用于帮助企业和组织识别和防御网络攻击。网络杀伤链模型将网络攻击过程分解为多个阶段,每个阶段都有特定的活动和目标。通过理解和监控这些阶段,防御者可以更有......
  • 自动化测试环境配置-selenium库和谷歌浏览器版
    浏览器和插件下载地址:通过网盘分享的文件:自动化测试安装包链接:https://pan.baidu.com/s/1acJJrA087zf_e02at3hoUg提取码:f83d第一步,取消谷歌浏览器的自动升级  再去控制面板卸载原来的谷歌浏览器  第二步,安装谷歌浏览器80版本  通过设置查看版本号,该版本是不会......
  • #渗透测试#SRC漏洞挖掘#蓝队基础之网络七层杀伤链03
    免责声明本教程仅为合法的教学目的而准备,严禁用于任何形式的违法犯罪活动及其他商业行为,在使用本教程前,您应确保该行为符合当地的法律法规,继续阅读即表示您需自行承担所有操作的后果,如有异议,请立即停止本文章阅读。                            ......
  • 删除团队关联索引单元测试
    理解了,如果你不能更改RespUtils类,我们可以在测试用例中直接检查BaseResponse对象的成功状态和其他属性。以下是更新后的单元测试代码,不依赖于RespUtils中的方法。更新后的单元测试代码importstaticorg.junit.jupiter.api.Assertions.*;importstaticorg.mockito.Mocki......