Merge branch 'dromara:v5-master' into v5-master

This commit is contained in:
gongxuanzhang
2022-03-09 17:03:38 +08:00
committed by GitHub
200 changed files with 5394 additions and 684 deletions

View File

@@ -0,0 +1,111 @@
package cn.hutool.core.builder;
import cn.hutool.core.util.StrUtil;
import lombok.Getter;
import lombok.Setter;
import lombok.ToString;
import lombok.experimental.Accessors;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
import java.util.Map;
/**
* {@link GenericBuilder} 单元测试类
*
* @author TomXin
*/
public class GenericBuilderTest {
@Test
public void test() {
Box box = GenericBuilder
.of(Box::new)
.with(Box::setId, 1024L)
.with(Box::setTitle, "Hello World!")
.with(Box::setLength, 9)
.with(Box::setWidth, 8)
.with(Box::setHeight, 7)
.build();
Assert.assertEquals(1024L, box.getId().longValue());
Assert.assertEquals("Hello World!", box.getTitle());
Assert.assertEquals(9, box.getLength().intValue());
Assert.assertEquals(8, box.getWidth().intValue());
Assert.assertEquals(7, box.getHeight().intValue());
// 对象修改
Box boxModified = GenericBuilder
.of(() -> box)
.with(Box::setTitle, "Hello Friend!")
.with(Box::setLength, 3)
.with(Box::setWidth, 4)
.with(Box::setHeight, 5)
.build();
Assert.assertEquals(1024L, boxModified.getId().longValue());
Assert.assertEquals("Hello Friend!", box.getTitle());
Assert.assertEquals(3, boxModified.getLength().intValue());
Assert.assertEquals(4, boxModified.getWidth().intValue());
Assert.assertEquals(5, boxModified.getHeight().intValue());
// 多参数构造
Box box1 = GenericBuilder
.of(Box::new, 2048L, "Hello Partner!", 222, 333, 444)
.with(Box::alis)
.build();
Assert.assertEquals(2048L, box1.getId().longValue());
Assert.assertEquals("Hello Partner!", box1.getTitle());
Assert.assertEquals(222, box1.getLength().intValue());
Assert.assertEquals(333, box1.getWidth().intValue());
Assert.assertEquals(444, box1.getHeight().intValue());
Assert.assertEquals("TomXin:\"Hello Partner!\"", box1.getTitleAlias());
}
@Test
public void buildMapTest(){
//Map创建
HashMap<String, String> colorMap = GenericBuilder
.of(HashMap<String,String>::new)
.with(Map::put, "red", "#FF0000")
.with(Map::put, "yellow", "#FFFF00")
.with(Map::put, "blue", "#0000FF")
.build();
Assert.assertEquals("#FF0000", colorMap.get("red"));
Assert.assertEquals("#FFFF00", colorMap.get("yellow"));
Assert.assertEquals("#0000FF", colorMap.get("blue"));
}
@Getter
@Setter
@ToString
@Accessors(chain = true)
public static class Box {
private Long id;
private String title;
private Integer length;
private Integer width;
private Integer height;
private String titleAlias;
public Box() {
}
public Box(Long id, String title, Integer length, Integer width, Integer height) {
this.id = id;
this.title = title;
this.length = length;
this.width = width;
this.height = height;
}
public void alis() {
if (StrUtil.isNotBlank(this.title)) {
this.titleAlias = "TomXin:\"" + title + "\"";
}
}
}
}

View File

@@ -0,0 +1,40 @@
package cn.hutool.core.codec;
import org.junit.Assert;
import org.junit.Test;
import java.nio.charset.StandardCharsets;
public class Base58Test {
@Test
public void encodeCheckedTest() {
String a = "hello world";
String encode = Base58.encodeChecked(0, a.getBytes());
Assert.assertEquals(1 + "3vQB7B6MrGQZaxCuFg4oh", encode);
// 无版本位
encode = Base58.encodeChecked(null, a.getBytes());
Assert.assertEquals("3vQB7B6MrGQZaxCuFg4oh", encode);
}
@Test
public void encodeTest() {
String a = "hello world";
String encode = Base58.encode(a.getBytes(StandardCharsets.UTF_8));
Assert.assertEquals("StV1DL6CwTryKyV", encode);
}
@Test
public void decodeCheckedTest() {
String a = "3vQB7B6MrGQZaxCuFg4oh";
byte[] decode = Base58.decodeChecked(1 + a);
Assert.assertArrayEquals("hello world".getBytes(StandardCharsets.UTF_8),decode);
decode = Base58.decodeChecked(a);
Assert.assertArrayEquals("hello world".getBytes(StandardCharsets.UTF_8),decode);
}
@Test
public void testDecode() {
String a = "StV1DL6CwTryKyV";
byte[] decode = Base58.decode(a);
Assert.assertArrayEquals("hello world".getBytes(StandardCharsets.UTF_8),decode);
}
}

View File

@@ -19,7 +19,7 @@ import java.util.Map;
public class ListUtilTest {
@Test
public void splitTest(){
public void splitTest() {
List<List<Object>> lists = ListUtil.split(null, 3);
Assert.assertEquals(ListUtil.empty(), lists);
@@ -60,7 +60,7 @@ public class ListUtilTest {
}
@Test
public void splitAvgTest(){
public void splitAvgTest() {
List<List<Object>> lists = ListUtil.splitAvg(null, 3);
Assert.assertEquals(ListUtil.empty(), lists);
@@ -80,13 +80,13 @@ public class ListUtilTest {
}
@Test(expected = IllegalArgumentException.class)
public void splitAvgNotZero(){
public void splitAvgNotZero() {
// limit不能小于等于0
ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 0);
}
@Test
public void editTest(){
public void editTest() {
List<String> a = ListUtil.toLinkedList("1", "2", "3");
final List<String> filter = (List<String>) CollUtil.edit(a, str -> "edit" + str);
Assert.assertEquals("edit1", filter.get(0));
@@ -104,7 +104,7 @@ public class ListUtilTest {
}
@Test
public void pageTest(){
public void pageTest() {
List<Integer> a = ListUtil.toLinkedList(1, 2, 3,4,5);
PageUtil.setFirstPageNo(1);
@@ -167,10 +167,13 @@ public class ListUtilTest {
Assert.assertArrayEquals(new int[]{}, pageListData.get(0).stream().mapToInt(Integer::valueOf).toArray());
Assert.assertArrayEquals(new int[]{3, 4}, pageListData.get(1).stream().mapToInt(Integer::valueOf).toArray());
Assert.assertArrayEquals(new int[]{5}, pageListData.get(2).stream().mapToInt(Integer::valueOf).toArray());
// 恢复默认值,避免影响其他测试用例
PageUtil.setFirstPageNo(0);
}
@Test
public void subTest(){
public void subTest() {
final List<Integer> of = ListUtil.of(1, 2, 3, 4);
final List<Integer> sub = ListUtil.sub(of, 2, 4);
sub.remove(0);
@@ -181,10 +184,10 @@ public class ListUtilTest {
}
@Test
public void sortByPropertyTest(){
public void sortByPropertyTest() {
@Data
@AllArgsConstructor
class TestBean{
class TestBean {
private int order;
private String name;
}
@@ -224,5 +227,9 @@ public class ListUtilTest {
ListUtil.swapElement(list, map2, map3);
Map<String, String> map = list.get(2);
Assert.assertEquals("李四", map.get("2"));
ListUtil.swapElement(list, map2, map1);
map = list.get(0);
Assert.assertEquals("李四", map.get("2"));
}
}

View File

@@ -65,6 +65,14 @@ public class ConvertTest {
Assert.assertEquals("a", result);
}
@Test
public void toStrTest4() {
// 被当作八进制
@SuppressWarnings("OctalInteger")
final String result = Convert.toStr(001200);
Assert.assertEquals("640", result);
}
@Test
public void toIntTest() {
String a = " 34232";

View File

@@ -1,15 +1,14 @@
package cn.hutool.core.convert;
import cn.hutool.core.date.DateUtil;
import org.junit.Assert;
import org.junit.Test;
import java.sql.Timestamp;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Date;
import org.junit.Assert;
import org.junit.Test;
import cn.hutool.core.date.DateUtil;
public class DateConvertTest {
@Test
@@ -28,7 +27,7 @@ public class DateConvertTest {
int dateLong = -1497600000;
Date value = Convert.toDate(dateLong);
Assert.assertNotNull(value);
Assert.assertEquals("Mon Dec 15 00:00:00 CST 1969", value.toString());
Assert.assertEquals("Mon Dec 15 00:00:00 CST 1969", value.toString().replace("GMT+08:00", "CST"));
final java.sql.Date sqlDate = Convert.convert(java.sql.Date.class, dateLong);
Assert.assertNotNull(sqlDate);
@@ -53,18 +52,18 @@ public class DateConvertTest {
java.sql.Date value2 = Convert.convert(java.sql.Date.class, timeLong);
Assert.assertEquals(timeLong, value2.getTime());
}
@Test
public void toLocalDateTimeTest() {
Date src = new Date();
LocalDateTime ldt = Convert.toLocalDateTime(src);
Assert.assertEquals(ldt, DateUtil.toLocalDateTime(src));
Timestamp ts = Timestamp.from(src.toInstant());
ldt = Convert.toLocalDateTime(ts);
Assert.assertEquals(ldt, DateUtil.toLocalDateTime(src));
String str = "2020-12-12 12:12:12.0";
ldt = Convert.toLocalDateTime(str);
Assert.assertEquals(ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")), str);

View File

@@ -175,6 +175,26 @@ public class NumberChineseFormatterTest {
Assert.assertEquals("零点零伍", f1);
}
@Test
public void formatSimpleTest() {
String f1 = NumberChineseFormatter.formatSimple(1_2345);
Assert.assertEquals("1.23万", f1);
f1 = NumberChineseFormatter.formatSimple(-5_5555);
Assert.assertEquals("-5.56万", f1);
f1 = NumberChineseFormatter.formatSimple(1_2345_6789);
Assert.assertEquals("1.23亿", f1);
f1 = NumberChineseFormatter.formatSimple(-5_5555_5555);
Assert.assertEquals("-5.56亿", f1);
f1 = NumberChineseFormatter.formatSimple(1_2345_6789_1011L);
Assert.assertEquals("1.23万亿", f1);
f1 = NumberChineseFormatter.formatSimple(-5_5555_5555_5555L);
Assert.assertEquals("-5.56万亿", f1);
f1 = NumberChineseFormatter.formatSimple(123);
Assert.assertEquals("123", f1);
f1 = NumberChineseFormatter.formatSimple(-123);
Assert.assertEquals("-123", f1);
}
@Test
public void digitToChineseTest() {
String digitToChinese = Convert.digitToChinese(12_4124_1241_2421.12);

View File

@@ -4,6 +4,8 @@ import cn.hutool.core.util.StrUtil;
import org.junit.Assert;
import org.junit.Test;
import java.util.Date;
public class ChineseDateTest {
@Test
@@ -105,4 +107,36 @@ public class ChineseDateTest {
Assert.assertEquals("戊申猴年 五月初五", c1.toString());
Assert.assertEquals("戊申猴年 闰五月初五", c2.toString());
}
@Test
public void getChineseMonthTest2(){
//https://github.com/dromara/hutool/issues/2112
ChineseDate springFestival = new ChineseDate(DateUtil.parseDate("2022-02-01"));
final String chineseMonth = springFestival.getChineseMonth();
Assert.assertEquals("一月", chineseMonth);
}
@Test
public void day19700101Test(){
// https://gitee.com/dromara/hutool/issues/I4UTPK
Date date = DateUtil.parse("1970-01-01");
ChineseDate chineseDate = new ChineseDate(date);
Assert.assertEquals("己酉鸡年 冬月廿四", chineseDate.toString());
date = DateUtil.parse("1970-01-02");
chineseDate = new ChineseDate(date);
Assert.assertEquals("己酉鸡年 冬月廿五", chineseDate.toString());
date = DateUtil.parse("1970-01-03");
chineseDate = new ChineseDate(date);
Assert.assertEquals("己酉鸡年 冬月廿六", chineseDate.toString());
}
@Test
public void day19000101Test(){
// 1900-01-31之前不支持
Date date = DateUtil.parse("1900-01-31");
ChineseDate chineseDate = new ChineseDate(date);
Assert.assertEquals("庚子鼠年 正月初一", chineseDate.toString());
}
}

View File

@@ -694,6 +694,8 @@ public class DateUtilTest {
String dateStr = "Wed Sep 16 11:26:23 CST 2009";
SimpleDateFormat sdf = new SimpleDateFormat(DatePattern.JDK_DATETIME_PATTERN, Locale.US);
// Asia/Shanghai是以地区命名的地区标准时在中国叫CST因此如果解析CST时不使用"Asia/Shanghai"而使用"GMT+08:00",会导致相差一个小时
sdf.setTimeZone(TimeZone.getTimeZone("Asia/Shanghai"));
final DateTime parse = DateUtil.parse(dateStr, sdf);
DateTime dateTime = DateUtil.parseCST(dateStr);
@@ -992,11 +994,13 @@ public class DateUtilTest {
@Test
public void parseSingleMonthAndDayTest() {
final DateTime parse = DateUtil.parse("2021-1-1");
DateTime parse = DateUtil.parse("2021-1-1");
Assert.assertNotNull(parse);
Assert.assertEquals("2021-01-01 00:00:00", parse.toString());
Console.log(DateUtil.parse("2021-1-22 00:00:00"));
parse = DateUtil.parse("2021-1-22 00:00:00");
Assert.assertNotNull(parse);
Assert.assertEquals("2021-01-22 00:00:00", parse.toString());
}
@Test
@@ -1004,4 +1008,43 @@ public class DateUtilTest {
final DateTime parse = DateUtil.parse("2021-12-01", DatePattern.NORM_DATE_FORMATTER);
Assert.assertEquals("2021-12-01 00:00:00", parse.toString());
}
@Test
public void isSameWeekTest() {
// 周六与周日比较
final boolean isSameWeek = DateUtil.isSameWeek(DateTime.of("2022-01-01", "yyyy-MM-dd"), DateTime.of("2022-01-02", "yyyy-MM-dd"), true);
Assert.assertTrue(isSameWeek);
// 周日与周一比较
final boolean isSameWeek1 = DateUtil.isSameWeek(DateTime.of("2022-01-02", "yyyy-MM-dd"), DateTime.of("2022-01-03", "yyyy-MM-dd"), false);
Assert.assertTrue(isSameWeek1);
// 跨月比较
final boolean isSameWeek2 = DateUtil.isSameWeek(DateTime.of("2021-12-29", "yyyy-MM-dd"), DateTime.of("2022-01-01", "yyyy-MM-dd"), true);
Assert.assertTrue(isSameWeek2);
}
@Test
public void parseTimeTest(){
final DateTime dateTime = DateUtil.parse("12:23:34");
Console.log(dateTime);
}
@Test
public void isOverlapTest() {
DateTime oneStartTime = DateUtil.parse("2022-01-01 10:10:10");
DateTime oneEndTime = DateUtil.parse("2022-01-01 11:10:10");
DateTime oneStartTime2 = DateUtil.parse("2022-01-01 11:20:10");
DateTime oneEndTime2 = DateUtil.parse("2022-01-01 11:30:10");
DateTime oneStartTime3 = DateUtil.parse("2022-01-01 11:40:10");
DateTime oneEndTime3 = DateUtil.parse("2022-01-01 11:50:10");
//真实请假数据
DateTime realStartTime = DateUtil.parse("2022-01-01 11:49:10");
DateTime realEndTime = DateUtil.parse("2022-01-01 12:00:10");
Assert.assertTrue(DateUtil.isOverlap(oneStartTime, oneEndTime, realStartTime, realEndTime));
Assert.assertTrue(DateUtil.isOverlap(oneStartTime2, oneEndTime2, realStartTime, realEndTime));
Assert.assertFalse(DateUtil.isOverlap(oneStartTime3, oneEndTime3, realStartTime, realEndTime));
}
}

View File

@@ -1,13 +1,16 @@
package cn.hutool.core.date;
import cn.hutool.core.lang.Console;
import org.junit.Assert;
import org.junit.Test;
import java.time.Duration;
import java.time.Instant;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.time.temporal.TemporalAccessor;
public class LocalDateTimeUtilTest {
@@ -197,4 +200,31 @@ public class LocalDateTimeUtilTest {
Assert.assertTrue(LocalDateTimeUtil.isOverlap(oneStartTime2,oneEndTime2,realStartTime,realEndTime));
Assert.assertFalse(LocalDateTimeUtil.isOverlap(oneStartTime3,oneEndTime3,realStartTime,realEndTime));
}
@Test
public void weekOfYearTest(){
LocalDate date1 = LocalDate.of(2021, 12, 31);
final int weekOfYear1 = LocalDateTimeUtil.weekOfYear(date1);
Assert.assertEquals(52, weekOfYear1);
final int weekOfYear2 = LocalDateTimeUtil.weekOfYear(date1.atStartOfDay());
Assert.assertEquals(52, weekOfYear2);
}
@Test
public void weekOfYearTest2(){
LocalDate date1 = LocalDate.of(2022, 1, 31);
final int weekOfYear1 = LocalDateTimeUtil.weekOfYear(date1);
Assert.assertEquals(5, weekOfYear1);
final int weekOfYear2 = LocalDateTimeUtil.weekOfYear(date1.atStartOfDay());
Assert.assertEquals(5, weekOfYear2);
}
@Test
public void ofTest2(){
final Instant instant = DateUtil.parse("2022-02-22").toInstant();
final LocalDateTime of = LocalDateTimeUtil.of((TemporalAccessor) instant);
Console.log(of);
}
}

View File

@@ -37,4 +37,15 @@ public class MonthTest {
lastDay = Month.of(Calendar.DECEMBER).getLastDay(true);
Assert.assertEquals(31, lastDay);
}
@Test
public void toJdkMonthTest(){
final java.time.Month month = Month.AUGUST.toJdkMonth();
Assert.assertEquals(java.time.Month.AUGUST, month);
}
@Test(expected = IllegalArgumentException.class)
public void toJdkMonthTest2(){
Month.UNDECIMBER.toJdkMonth();
}
}

View File

@@ -21,11 +21,8 @@ public class CheckedUtilTest {
@Test
public void sleepTest() {
VoidFunc0 func = () -> Thread.sleep(1000L);
func.callWithRuntimeException();
}
@@ -39,10 +36,8 @@ public class CheckedUtilTest {
} catch (Exception re) {
Assert.assertTrue(re instanceof RuntimeException);
}
}
@SuppressWarnings("ConstantConditions")
@Test
public void functionTest() {
Func1<String, String> afunc = (funcParam) -> {

View File

@@ -452,4 +452,26 @@ public class FileUtilTest {
List<String> list = ListUtil.toList("a", "b", "c");
FileUtil.appendLines(list, FileUtil.file("d:/test/appendLines.txt"), CharsetUtil.CHARSET_UTF_8);
}
@Test
@Ignore
public void createTempFileTest(){
File nullDirTempFile = FileUtil.createTempFile();
Assert.assertTrue(nullDirTempFile.exists());
File suffixDirTempFile = FileUtil.createTempFile(".xlsx",true);
Assert.assertEquals("xlsx", FileUtil.getSuffix(suffixDirTempFile));
File prefixDirTempFile = FileUtil.createTempFile("prefix",".xlsx",true);
Assert.assertTrue(FileUtil.getPrefix(prefixDirTempFile).startsWith("prefix"));
}
@Test
@Ignore
public void getTotalLinesTest() {
// 千万行秒级内返回
final int totalLines = FileUtil.getTotalLines(FileUtil.file(""));
Assert.assertEquals(10000000, totalLines);
}
}

View File

@@ -4,6 +4,7 @@ import cn.hutool.core.date.DateField;
import cn.hutool.core.date.DateRange;
import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;
import org.junit.Assert;
import org.junit.Test;
@@ -12,8 +13,8 @@ import java.util.NoSuchElementException;
/**
* {@link Range} 单元测试
* @author Looly
*
* @author Looly
*/
public class RangeTest {
@@ -36,6 +37,32 @@ public class RangeTest {
Assert.assertFalse(range.hasNext());
}
@Test
public void dateRangeFuncTest() {
DateTime start = DateUtil.parse("2021-01-01");
DateTime end = DateUtil.parse("2021-01-03");
List<Integer> dayOfMonthList = DateUtil.rangeFunc(start, end, DateField.DAY_OF_YEAR, a -> DateTime.of(a).dayOfMonth());
Assert.assertArrayEquals(dayOfMonthList.toArray(new Integer[]{}), new Integer[]{1, 2, 3});
List<Integer> dayOfMonthList2 = DateUtil.rangeFunc(null, null, DateField.DAY_OF_YEAR, a -> DateTime.of(a).dayOfMonth());
Assert.assertArrayEquals(dayOfMonthList2.toArray(new Integer[]{}), new Integer[]{});
}
@Test
public void dateRangeConsumeTest() {
DateTime start = DateUtil.parse("2021-01-01");
DateTime end = DateUtil.parse("2021-01-03");
StringBuilder sb = new StringBuilder();
DateUtil.rangeConsume(start, end, DateField.DAY_OF_YEAR, a -> sb.append(DateTime.of(a).dayOfMonth()).append("#"));
Assert.assertEquals(sb.toString(), "1#2#3#");
StringBuilder sb2 = new StringBuilder();
DateUtil.rangeConsume(null, null, DateField.DAY_OF_YEAR, a -> sb2.append(DateTime.of(a).dayOfMonth()).append("#"));
Assert.assertEquals(sb2.toString(), StrUtil.EMPTY);
}
@Test
public void dateRangeTest2() {
DateTime start = DateUtil.parse("2021-01-31");
@@ -84,7 +111,7 @@ public class RangeTest {
}
@Test
public void rangeDayOfYearTest(){
public void rangeDayOfYearTest() {
DateTime start = DateUtil.parse("2017-01-01");
DateTime end = DateUtil.parse("2017-01-05");
@@ -109,4 +136,39 @@ public class RangeTest {
Assert.assertEquals(DateUtil.parse("2017-01-01"), rangeToList.get(0));
Assert.assertEquals(DateUtil.parse("2017-01-02"), rangeToList.get(1));
}
@Test
public void rangeContains() {
// 开始区间
DateTime start = DateUtil.parse("2017-01-01");
DateTime end = DateUtil.parse("2017-01-31");
DateRange startRange = DateUtil.range(start, end, DateField.DAY_OF_YEAR);
// 结束区间
DateTime start1 = DateUtil.parse("2017-01-31");
DateTime end1 = DateUtil.parse("2017-02-02");
DateRange endRange = DateUtil.range(start1, end1, DateField.DAY_OF_YEAR);
// 交集
List<DateTime> dateTimes = DateUtil.rangeContains(startRange, endRange);
Assert.assertEquals(1, dateTimes.size());
Assert.assertEquals(DateUtil.parse("2017-01-31"), dateTimes.get(0));
}
@Test
public void rangeNotContains() {
// 开始区间
DateTime start = DateUtil.parse("2017-01-01");
DateTime end = DateUtil.parse("2017-01-30");
DateRange startRange = DateUtil.range(start, end, DateField.DAY_OF_YEAR);
// 结束区间
DateTime start1 = DateUtil.parse("2017-01-01");
DateTime end1 = DateUtil.parse("2017-01-31");
DateRange endRange = DateUtil.range(start1, end1, DateField.DAY_OF_YEAR);
// 差集
List<DateTime> dateTimes1 = DateUtil.rangeNotContains(startRange, endRange);
Assert.assertEquals(1, dateTimes1.size());
Assert.assertEquals(DateUtil.parse("2017-01-31"), dateTimes1.get(0));
}
}

View File

@@ -0,0 +1,36 @@
package cn.hutool.core.lang.hash;
import cn.hutool.core.util.StrUtil;
import org.junit.Assert;
import org.junit.Test;
public class CityHashTest {
@Test
public void hash32Test() {
int hv = CityHash.hash32(StrUtil.utf8Bytes(""));
Assert.assertEquals(1290029860, hv);
hv = CityHash.hash32(StrUtil.utf8Bytes("你好"));
Assert.assertEquals(1374181357, hv);
hv = CityHash.hash32(StrUtil.utf8Bytes("见到你很高兴"));
Assert.assertEquals(1475516842, hv);
hv = CityHash.hash32(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(0x51020cae, hv);
}
@Test
public void hash64Test() {
long hv = CityHash.hash64(StrUtil.utf8Bytes(""));
Assert.assertEquals(-4296898700418225525L, hv);
hv = CityHash.hash64(StrUtil.utf8Bytes("你好"));
Assert.assertEquals(-4294276205456761303L, hv);
hv = CityHash.hash64(StrUtil.utf8Bytes("见到你很高兴"));
Assert.assertEquals(272351505337503793L, hv);
hv = CityHash.hash64(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(-8234735310919228703L, hv);
}
}

View File

@@ -0,0 +1,93 @@
package cn.hutool.core.lang.hash;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
/**
* https://gitee.com/dromara/hutool/pulls/532
*/
public class MetroHashTest {
@Test
public void testEmpty() {
Assert.assertEquals("31290877cceaea29", HexUtil.toHex(MetroHash.hash64(StrUtil.utf8Bytes(""), 0)));
}
@Test
public void metroHash64Test() {
byte[] str = "我是一段测试123".getBytes(CharsetUtil.CHARSET_UTF_8);
final long hash64 = MetroHash.hash64(str);
Assert.assertEquals(62920234463891865L, hash64);
}
@Test
public void metroHash128Test() {
byte[] str = "我是一段测试123".getBytes(CharsetUtil.CHARSET_UTF_8);
final long[] hash128 = MetroHash.hash128(str).getLongArray();
Assert.assertEquals(4956592424592439349L, hash128[0]);
Assert.assertEquals(6301214698325086246L, hash128[1]);
}
/**
* 数据量越大 MetroHash 优势越明显,
*/
@Test
@Ignore
public void bulkHashing64Test() {
String[] strArray = getRandomStringArray();
long startCity = System.currentTimeMillis();
for (String s : strArray) {
CityHash.hash64(s.getBytes());
}
long endCity = System.currentTimeMillis();
long startMetro = System.currentTimeMillis();
for (String s : strArray) {
MetroHash.hash64(StrUtil.utf8Bytes(s));
}
long endMetro = System.currentTimeMillis();
System.out.println("metroHash =============" + (endMetro - startMetro));
System.out.println("cityHash =============" + (endCity - startCity));
}
/**
* 数据量越大 MetroHash 优势越明显,
*/
@Test
@Ignore
public void bulkHashing128Test() {
String[] strArray = getRandomStringArray();
long startCity = System.currentTimeMillis();
for (String s : strArray) {
CityHash.hash128(s.getBytes());
}
long endCity = System.currentTimeMillis();
long startMetro = System.currentTimeMillis();
for (String s : strArray) {
MetroHash.hash128(StrUtil.utf8Bytes(s));
}
long endMetro = System.currentTimeMillis();
System.out.println("metroHash =============" + (endMetro - startMetro));
System.out.println("cityHash =============" + (endCity - startCity));
}
private static String[] getRandomStringArray() {
String[] result = new String[10000000];
int index = 0;
while (index < 10000000) {
result[index++] = RandomUtil.randomString(RandomUtil.randomInt(64));
}
return result;
}
}

View File

@@ -0,0 +1,36 @@
package cn.hutool.core.lang.hash;
import cn.hutool.core.util.StrUtil;
import org.junit.Assert;
import org.junit.Test;
public class MurMurHashTest {
@Test
public void hash32Test() {
int hv = MurmurHash.hash32(StrUtil.utf8Bytes(""));
Assert.assertEquals(222142701, hv);
hv = MurmurHash.hash32(StrUtil.utf8Bytes("你好"));
Assert.assertEquals(1188098267, hv);
hv = MurmurHash.hash32(StrUtil.utf8Bytes("见到你很高兴"));
Assert.assertEquals(-1898490321, hv);
hv = MurmurHash.hash32(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(-1713131054, hv);
}
@Test
public void hash64Test() {
long hv = MurmurHash.hash64(StrUtil.utf8Bytes(""));
Assert.assertEquals(-1349759534971957051L, hv);
hv = MurmurHash.hash64(StrUtil.utf8Bytes("你好"));
Assert.assertEquals(-7563732748897304996L, hv);
hv = MurmurHash.hash64(StrUtil.utf8Bytes("见到你很高兴"));
Assert.assertEquals(-766658210119995316L, hv);
hv = MurmurHash.hash64(StrUtil.utf8Bytes("我们将通过生成一个大的文件的方式来检验各种方法的执行效率因为这种方式在结束的时候需要执行文件"));
Assert.assertEquals(-7469283059271653317L, hv);
}
}

View File

@@ -348,4 +348,19 @@ public class UrlBuilderTest {
builder.setFragment(builder.getFragment() + "?timestamp=1640391380204");
Assert.assertEquals("https://www.hutool.cn/#/a/b?timestamp=1640391380204", builder.toString());
}
@Test
public void paramWithPlusTest(){
String url = "http://127.0.0.1/?" +
"Expires=1642734164&" +
"security-token=CAIS+AF1q6Ft5B2yfSjIr5fYEeju1b1ggpPee2KGpjlgQtdfl43urjz2IHtKdXRvBu8Xs" +
"/4wnmxX7f4YlqB6T55OSAmcNZEoPwKpT4zmMeT7oMWQweEurv" +
"/MQBqyaXPS2MvVfJ+OLrf0ceusbFbpjzJ6xaCAGxypQ12iN+/m6" +
"/Ngdc9FHHPPD1x8CcxROxFppeIDKHLVLozNCBPxhXfKB0ca0WgVy0EHsPnvm5DNs0uH1AKjkbRM9r6ceMb0M5NeW75kSMqw0eBMca7M7TVd8RAi9t0t1" +
"/IVpGiY4YDAWQYLv0rda7DOltFiMkpla7MmXqlft+hzcgeQY0pc" +
"/RqAAYRYVCBiyuzAexSiDiJX1VqWljg4jYp1sdyv3HpV3sXVcf6VH6AN9ot5YNTw4JNO0aNpLpLm93rRMrOKIOsve+OmNyZ4HS7qHQKt1qp7HY1A" +
"/wGhJstkAoGQt+CHSMwVdIx3bVT1+ZYnJdM/oIQ/90afw4EEEQaRE51Z0rQC7z8d";
final String build = UrlBuilder.of(url).build();
Assert.assertEquals(url, build);
}
}

View File

@@ -137,4 +137,11 @@ public class UrlQueryTest {
final UrlQuery query = UrlQuery.of(queryStr, null);
Assert.assertEquals(queryStr, query.toString());
}
@Test
public void parsePercentTest2(){
String queryStr = "signature=%2Br1ekUCGjXiu50Y%2Bk0MO4ovulK8%3D";
final UrlQuery query = UrlQuery.of(queryStr, null);
Assert.assertEquals(queryStr, query.toString());
}
}

View File

@@ -0,0 +1,115 @@
package cn.hutool.core.text;
import org.junit.Assert;
import org.junit.Test;
import java.util.HashMap;
public class AntPathMatcherTest {
@Test
public void matchesTest() {
AntPathMatcher antPathMatcher = new AntPathMatcher();
boolean matched = antPathMatcher.match("/api/org/organization/{orgId}", "/api/org/organization/999");
Assert.assertTrue(matched);
}
@Test
public void matchesTest2() {
AntPathMatcher antPathMatcher = new AntPathMatcher();
String pattern = "/**/*.xml*";
String path = "/WEB-INF/web.xml";
boolean isMatched = antPathMatcher.match(pattern, path);
Assert.assertTrue(isMatched);
pattern = "org/codelabor/*/**/*Service";
path = "org/codelabor/example/HelloWorldService";
isMatched = antPathMatcher.match(pattern, path);
Assert.assertTrue(isMatched);
pattern = "org/codelabor/*/**/*Service?";
path = "org/codelabor/example/HelloWorldServices";
isMatched = antPathMatcher.match(pattern, path);
Assert.assertTrue(isMatched);
}
@Test
public void matchesTest3(){
AntPathMatcher pathMatcher = new AntPathMatcher();
pathMatcher.setCachePatterns(true);
pathMatcher.setCaseSensitive(true);
pathMatcher.setPathSeparator("/");
pathMatcher.setTrimTokens(true);
Assert.assertTrue(pathMatcher.match("a", "a"));
Assert.assertTrue(pathMatcher.match("a*", "ab"));
Assert.assertTrue(pathMatcher.match("a*/**/a", "ab/asdsa/a"));
Assert.assertTrue(pathMatcher.match("a*/**/a", "ab/asdsa/asdasd/a"));
Assert.assertTrue(pathMatcher.match("*", "a"));
Assert.assertTrue(pathMatcher.match("*/*", "a/a"));
}
/**
* AntPathMatcher默认路径分隔符为“/”而在匹配文件路径时需要注意Windows下路径分隔符为“\”Linux下为“/”。靠谱写法如下两种方式:
* AntPathMatcher matcher = new AntPathMatcher(File.separator);
* AntPathMatcher matcher = new AntPathMatcher(System.getProperty("file.separator"));
*/
@Test
public void matchesTest4() {
AntPathMatcher pathMatcher = new AntPathMatcher();
// 精确匹配
Assert.assertTrue(pathMatcher.match("/test", "/test"));
Assert.assertFalse(pathMatcher.match("test", "/test"));
//测试通配符?
Assert.assertTrue(pathMatcher.match("t?st", "test"));
Assert.assertTrue(pathMatcher.match("te??", "test"));
Assert.assertFalse(pathMatcher.match("tes?", "tes"));
Assert.assertFalse(pathMatcher.match("tes?", "testt"));
//测试通配符*
Assert.assertTrue(pathMatcher.match("*", "test"));
Assert.assertTrue(pathMatcher.match("test*", "test"));
Assert.assertTrue(pathMatcher.match("test/*", "test/Test"));
Assert.assertTrue(pathMatcher.match("*.*", "test."));
Assert.assertTrue(pathMatcher.match("*.*", "test.test.test"));
Assert.assertFalse(pathMatcher.match("test*", "test/")); //注意这里是false 因为路径不能用*匹配
Assert.assertFalse(pathMatcher.match("test*", "test/t")); //这同理
Assert.assertFalse(pathMatcher.match("test*aaa", "testblaaab")); //这个是false 因为最后一个b无法匹配了 前面都是能匹配成功的
//测试通配符** 匹配多级URL
Assert.assertTrue(pathMatcher.match("/*/**", "/testing/testing"));
Assert.assertTrue(pathMatcher.match("/**/*", "/testing/testing"));
Assert.assertTrue(pathMatcher.match("/bla/**/bla", "/bla/testing/testing/bla/bla")); //这里也是true哦
Assert.assertFalse(pathMatcher.match("/bla*bla/test", "/blaXXXbl/test"));
Assert.assertFalse(pathMatcher.match("/????", "/bala/bla"));
Assert.assertFalse(pathMatcher.match("/**/*bla", "/bla/bla/bla/bbb"));
Assert.assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing/"));
Assert.assertTrue(pathMatcher.match("/*bla*/**/bla/*", "/XXXblaXXXX/testing/testing/bla/testing"));
Assert.assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing"));
Assert.assertTrue(pathMatcher.match("/*bla*/**/bla/**", "/XXXblaXXXX/testing/testing/bla/testing/testing.jpg"));
Assert.assertTrue(pathMatcher.match("/foo/bar/**", "/foo/bar"));
//这个需要特别注意:{}里面的相当于Spring MVC里接受一个参数一样所以任何东西都会匹配的
Assert.assertTrue(pathMatcher.match("/{bla}.*", "/testing.html"));
Assert.assertFalse(pathMatcher.match("/{bla}.htm", "/testing.html")); //这样就是false了
}
/**
* 测试 URI 模板变量提取
*/
@Test
public void testExtractUriTemplateVariables() {
AntPathMatcher antPathMatcher = new AntPathMatcher();
HashMap<String, String> map = (HashMap<String, String>) antPathMatcher.extractUriTemplateVariables("/api/org/organization/{orgId}",
"/api/org" +
"/organization" +
"/999");
Assert.assertEquals(1, map.size());
}
}

View File

@@ -22,6 +22,13 @@ public class CharSequenceUtilTest {
Assert.assertEquals(replace, result);
}
@Test
public void replaceByStrTest(){
String replace = "SSM15930297701BeryAllen";
String result = CharSequenceUtil.replace(replace, 5, 12, "***");
Assert.assertEquals("SSM15***01BeryAllen", result);
}
@Test
public void addPrefixIfNotTest(){
String str = "hutool";

View File

@@ -12,4 +12,10 @@ public class NamingCaseTest {
.set("customerNickV2", "customer_nick_v2")
.forEach((key, value) -> Assert.assertEquals(value, NamingCase.toUnderlineCase(key)));
}
@Test
public void toUnderLineCaseTest2(){
final String wPRunOZTime = NamingCase.toUnderlineCase("wPRunOZTime");
Assert.assertEquals("w_P_run_OZ_time", wPRunOZTime);
}
}

View File

@@ -78,4 +78,25 @@ public class StrJoinerTest {
.append("3");
Assert.assertEquals("[1],[2],[3]", append.toString());
}
@Test
public void lengthTest(){
StrJoiner joiner = StrJoiner.of(",", "[", "]");
Assert.assertEquals(joiner.toString().length(), joiner.length());
joiner.append("123");
Assert.assertEquals(joiner.toString().length(), joiner.length());
}
@Test
public void mergeTest(){
StrJoiner joiner1 = StrJoiner.of(",", "[", "]");
joiner1.append("123");
StrJoiner joiner2 = StrJoiner.of(",", "[", "]");
joiner1.append("456");
joiner1.append("789");
final StrJoiner merge = joiner1.merge(joiner2);
Assert.assertEquals("[123,456,789]", merge.toString());
}
}

View File

@@ -8,7 +8,7 @@ import org.junit.Test;
import java.io.StringReader;
public class CsvParserTest {
@Test
public void parseTest1() {
StringReader reader = StrUtil.getReader("aaa,b\"bba\",ccc");
@@ -18,7 +18,7 @@ public class CsvParserTest {
Assert.assertEquals("b\"bba\"", row.getRawList().get(1));
IoUtil.close(parser);
}
@Test
public void parseTest2() {
StringReader reader = StrUtil.getReader("aaa,\"bba\"bbb,ccc");
@@ -28,7 +28,7 @@ public class CsvParserTest {
Assert.assertEquals("\"bba\"bbb", row.getRawList().get(1));
IoUtil.close(parser);
}
@Test
public void parseTest3() {
StringReader reader = StrUtil.getReader("aaa,\"bba\",ccc");
@@ -38,7 +38,7 @@ public class CsvParserTest {
Assert.assertEquals("bba", row.getRawList().get(1));
IoUtil.close(parser);
}
@Test
public void parseTest4() {
StringReader reader = StrUtil.getReader("aaa,\"\",ccc");
@@ -48,4 +48,16 @@ public class CsvParserTest {
Assert.assertEquals("", row.getRawList().get(1));
IoUtil.close(parser);
}
@Test
public void parseEscapeTest(){
// https://datatracker.ietf.org/doc/html/rfc4180#section-2
// 第七条规则
StringReader reader = StrUtil.getReader("\"b\"\"bb\"");
CsvParser parser = new CsvParser(reader, null);
CsvRow row = parser.nextRow();
Assert.assertNotNull(row);
Assert.assertEquals(1, row.size());
Assert.assertEquals("b\"bb", row.get(0));
}
}

View File

@@ -19,6 +19,8 @@ public class CsvWriterTest {
CharsetUtil.CHARSET_GBK, false, csvWriteConfig);
writer.writeHeaderLine("name", "gender", "address");
writer.writeLine("张三", "", "XX市XX区");
writer.writeLine("李四", "", "XX市XX区,01号");
writer.close();
}
}

View File

@@ -459,4 +459,11 @@ public class ArrayUtilTest {
Assert.assertEquals(3, arrayAfterSplit.length);
Assert.assertEquals(24, arrayAfterSplit[2].length);
}
@Test
public void getTest(){
String[] a = {"a", "b", "c"};
final Object o = ArrayUtil.get(a, -1);
Assert.assertEquals("c", o);
}
}

View File

@@ -10,9 +10,16 @@ public class ByteUtilTest {
@Test
public void intAndBytesLittleEndianTest() {
// 测试 int 转小端序 byte 数组
int int1 = RandomUtil.randomInt();
int int1 = RandomUtil.randomInt((Integer.MAX_VALUE));
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putInt(int1);
byte[] bytesIntFromBuffer = buffer.array();
byte[] bytesInt = ByteUtil.intToBytes(int1, ByteOrder.LITTLE_ENDIAN);
Assert.assertArrayEquals(bytesIntFromBuffer, bytesInt);
int int2 = ByteUtil.bytesToInt(bytesInt, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(int1, int2);
@@ -28,8 +35,14 @@ public class ByteUtilTest {
@Test
public void intAndBytesBigEndianTest() {
// 测试 int 转大端序 byte 数组
int int2 = RandomUtil.randomInt();
int int2 = RandomUtil.randomInt(Integer.MAX_VALUE);
ByteBuffer buffer = ByteBuffer.allocate(Integer.BYTES);
buffer.putInt(int2);
byte[] bytesIntFromBuffer = buffer.array();
byte[] bytesInt = ByteUtil.intToBytes(int2, ByteOrder.BIG_ENDIAN);
Assert.assertArrayEquals(bytesIntFromBuffer, bytesInt);
// 测试大端序 byte 数组转 int
int int3 = ByteUtil.bytesToInt(bytesInt, ByteOrder.BIG_ENDIAN);
@@ -39,9 +52,16 @@ public class ByteUtilTest {
@Test
public void longAndBytesLittleEndianTest() {
// 测试 long 转 byte 数组
long long1 = 2223;
long long1 = RandomUtil.randomLong(Long.MAX_VALUE);
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.order(ByteOrder.LITTLE_ENDIAN);
buffer.putLong(long1);
byte[] bytesLongFromBuffer = buffer.array();
byte[] bytesLong = ByteUtil.longToBytes(long1, ByteOrder.LITTLE_ENDIAN);
Assert.assertArrayEquals(bytesLongFromBuffer, bytesLong);
long long2 = ByteUtil.bytesToLong(bytesLong, ByteOrder.LITTLE_ENDIAN);
Assert.assertEquals(long1, long2);
@@ -57,11 +77,16 @@ public class ByteUtilTest {
@Test
public void longAndBytesBigEndianTest() {
// 测试大端序 long 转 byte 数组
long long1 = 2223;
long long1 = RandomUtil.randomLong(Long.MAX_VALUE);
ByteBuffer buffer = ByteBuffer.allocate(Long.BYTES);
buffer.putLong(long1);
byte[] bytesLongFromBuffer = buffer.array();
byte[] bytesLong = ByteUtil.longToBytes(long1, ByteOrder.BIG_ENDIAN);
long long2 = ByteUtil.bytesToLong(bytesLong, ByteOrder.BIG_ENDIAN);
Assert.assertArrayEquals(bytesLongFromBuffer, bytesLong);
long long2 = ByteUtil.bytesToLong(bytesLong, ByteOrder.BIG_ENDIAN);
Assert.assertEquals(long1, long2);
}

View File

@@ -11,37 +11,46 @@ import org.junit.Test;
*/
public class CoordinateUtilTest {
@Test
public void wgs84ToGcj02Test(){
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.wgs84ToGcj02(116.404, 39.915);
Assert.assertEquals(116.41033392216508D, coordinate.getLng(), 15);
Assert.assertEquals(39.91640428150164D, coordinate.getLat(), 15);
}
@Test
public void gcj02ToWgs84Test(){
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.gcj02ToWgs84(116.404, 39.915);
Assert.assertEquals(116.39766607783491D, coordinate.getLng(), 15);
Assert.assertEquals(39.91359571849836D, coordinate.getLat(), 15);
}
@Test
public void wgs84toBd09Test(){
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.wgs84ToBd09(116.404, 39.915);
Assert.assertEquals(116.41671695444782D, coordinate.getLng(), 15);
Assert.assertEquals(39.922698713521726D, coordinate.getLat(), 15);
}
@Test
public void bd09toWgs84Test(){
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.bd09toWgs84(116.404, 39.915);
Assert.assertEquals(116.39129143419822D, coordinate.getLng(), 15);
Assert.assertEquals(39.907253214522164D, coordinate.getLat(), 15);
}
@Test
public void gcj02ToBd09Test() {
final CoordinateUtil.Coordinate gcj02 = CoordinateUtil.gcj02ToBd09(116.404, 39.915);
Assert.assertEquals(116.41036949371029D, gcj02.getLng(), 15);
Assert.assertEquals(39.92133699351021D, gcj02.getLat(), 15);
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.gcj02ToBd09(116.404, 39.915);
Assert.assertEquals(116.41036949371029D, coordinate.getLng(), 15);
Assert.assertEquals(39.92133699351022D, coordinate.getLat(), 15);
}
@Test
public void bd09toGcj02Test(){
final CoordinateUtil.Coordinate gcj02 = CoordinateUtil.bd09ToGcj02(116.404, 39.915);
Assert.assertEquals(116.39762729119315D, gcj02.getLng(), 15);
Assert.assertEquals(39.90865673957631D, gcj02.getLat(), 15);
}
@Test
public void gcj02ToWgs84(){
final CoordinateUtil.Coordinate gcj02 = CoordinateUtil.wgs84ToGcj02(116.404, 39.915);
Assert.assertEquals(116.39775550083061D, gcj02.getLng(), 15);
Assert.assertEquals(39.91359571849836D, gcj02.getLat(), 15);
}
@Test
public void wgs84ToGcj02Test(){
final CoordinateUtil.Coordinate gcj02 = CoordinateUtil.wgs84ToGcj02(116.404, 39.915);
Assert.assertEquals(116.41024449916938D, gcj02.getLng(), 15);
Assert.assertEquals(39.91640428150164D, gcj02.getLat(), 15);
}
@Test
public void wgs84toBd09(){
final CoordinateUtil.Coordinate coordinate = CoordinateUtil.bd09ToGcj02(116.404, 39.915);
Assert.assertEquals(116.39762729119315D, coordinate.getLng(), 15);
Assert.assertEquals(39.90865673957631D, coordinate.getLat(), 15);
}
}

View File

@@ -17,9 +17,17 @@ public class CreditCodeUtilTest {
Assert.assertTrue(CreditCodeUtil.isCreditCode(testCreditCode));
}
@Test
public void isCreditCode2() {
// 由于早期部分试点地区推行 法人和其他组织统一社会信用代码 较早,会存在部分代码不符合国家标准的情况。
// 见https://github.com/bluesky335/IDCheck
String testCreditCode = "91350211M00013FA1N";
Assert.assertFalse(CreditCodeUtil.isCreditCode(testCreditCode));
}
@Test
public void randomCreditCode() {
final String s = CreditCodeUtil.randomCreditCode();
Assert.assertTrue(CreditCodeUtil.isCreditCode(s));
}
}
}

View File

@@ -5,32 +5,31 @@ import org.junit.Test;
/**
* 分页单元测试
* @author Looly
*
* @author Looly
*/
public class PageUtilTest {
@Test
public void transToStartEndTest(){
PageUtil.setFirstPageNo(0);
public void transToStartEndTest() {
int[] startEnd1 = PageUtil.transToStartEnd(0, 10);
Assert.assertEquals(0, startEnd1[0]);
Assert.assertEquals(10, startEnd1[1]);
int[] startEnd2 = PageUtil.transToStartEnd(1, 10);
Assert.assertEquals(10, startEnd2[0]);
Assert.assertEquals(20, startEnd2[1]);
}
@Test
public void totalPage(){
public void totalPage() {
int totalPage = PageUtil.totalPage(20, 3);
Assert.assertEquals(7, totalPage);
}
@Test
public void rainbowTest() {
int[] rainbow = PageUtil.rainbow(5, 20, 6);
Assert.assertArrayEquals(new int[] {3, 4, 5, 6, 7, 8}, rainbow);
Assert.assertArrayEquals(new int[]{3, 4, 5, 6, 7, 8}, rainbow);
}
}

View File

@@ -1,8 +1,13 @@
package cn.hutool.core.util;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.date.TimeInterval;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.test.bean.ExamInfoDict;
import cn.hutool.core.util.ClassUtilTest.TestSubClass;
import lombok.Data;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import java.lang.reflect.Field;
@@ -91,33 +96,77 @@ public class ReflectUtilTest {
@Test
public void noneStaticInnerClassTest() {
final TestAClass testAClass = ReflectUtil.newInstanceIfPossible(TestAClass.class);
final NoneStaticClass testAClass = ReflectUtil.newInstanceIfPossible(NoneStaticClass.class);
Assert.assertNotNull(testAClass);
Assert.assertEquals(2, testAClass.getA());
}
@Data
static class TestClass {
private int a;
public int getA() {
return a;
}
public void setA(int a) {
this.a = a;
}
}
@Data
@SuppressWarnings("InnerClassMayBeStatic")
class TestAClass {
class NoneStaticClass {
private int a = 2;
}
public int getA() {
return a;
@Test
@Ignore
public void getMethodBenchTest(){
// 预热
getMethod(TestBenchClass.class, false, "getH");
final TimeInterval timer = DateUtil.timer();
timer.start();
for (int i = 0; i < 100000000; i++) {
ReflectUtil.getMethod(TestBenchClass.class, false, "getH");
}
Console.log(timer.interval());
timer.restart();
for (int i = 0; i < 100000000; i++) {
getMethod(TestBenchClass.class, false, "getH");
}
Console.log(timer.interval());
}
@Data
static class TestBenchClass {
private int a;
private String b;
private String c;
private String d;
private String e;
private String f;
private String g;
private String h;
private String i;
private String j;
private String k;
private String l;
private String m;
private String n;
}
public static Method getMethod(Class<?> clazz, boolean ignoreCase, String methodName, Class<?>... paramTypes) throws SecurityException {
if (null == clazz || StrUtil.isBlank(methodName)) {
return null;
}
public void setA(int a) {
this.a = a;
Method res = null;
final Method[] methods = ReflectUtil.getMethods(clazz);
if (ArrayUtil.isNotEmpty(methods)) {
for (Method method : methods) {
if (StrUtil.equals(methodName, method.getName(), ignoreCase)
&& ClassUtil.isAllAssignableFrom(method.getParameterTypes(), paramTypes)
&& (res == null
|| res.getReturnType().isAssignableFrom(method.getReturnType()))) {
res = method;
}
}
}
return res;
}
}

View File

@@ -186,4 +186,13 @@ public class ZipUtilTest {
ZipUtil.zip(out, new String[]{"sm1_alias.txt"},
new InputStream[]{FileUtil.getInputStream("d:/test/sm4_1.txt")});
}
@Test
@Ignore
public void zipMultiFileTest(){
File[] dd={FileUtil.file("d:\\test\\qr_a.jpg")
,FileUtil.file("d:\\test\\qr_b.jpg")};
ZipUtil.zip(FileUtil.file("d:\\test\\qr.zip"),false,dd);
}
}