IpAdressServiceImpl的测试
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
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])$");
}
}