单元测试由Junit4变更为Junit5

This commit is contained in:
Looly 2024-08-09 14:32:30 +08:00
parent 155c43a6a3
commit c7e0bc5d9f
568 changed files with 7794 additions and 7671 deletions

View File

@ -21,6 +21,7 @@
* 【mail 】 增加文字颜色与背景颜色色差设置pr#1252@gitee * 【mail 】 增加文字颜色与背景颜色色差设置pr#1252@gitee
* 【mail 】 XmlUtil增加xmlToBean重载支持CopyOptions参数issue#IAISBB@gitee * 【mail 】 XmlUtil增加xmlToBean重载支持CopyOptions参数issue#IAISBB@gitee
* 【core 】 增加默认色差方法pr#1257@gitee * 【core 】 增加默认色差方法pr#1257@gitee
* 【all 】 单元测试由Junit4变更为Junit5
### 🐞Bug修复 ### 🐞Bug修复
* 【core 】 修复因RFC3986理解有误导致的UrlPath处理冒号转义问题issue#IAAE88@Gitee * 【core 】 修复因RFC3986理解有误导致的UrlPath处理冒号转义问题issue#IAAE88@Gitee

View File

@ -4,8 +4,8 @@ import cn.hutool.aop.ProxyUtil;
import cn.hutool.aop.aspects.TimeIntervalAspect; import cn.hutool.aop.aspects.TimeIntervalAspect;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* AOP模块单元测试 * AOP模块单元测试
@ -18,7 +18,7 @@ public class AopTest {
public void aopTest() { public void aopTest() {
Animal cat = ProxyUtil.proxy(new Cat(), TimeIntervalAspect.class); Animal cat = ProxyUtil.proxy(new Cat(), TimeIntervalAspect.class);
String result = cat.eat(); String result = cat.eat();
Assert.assertEquals("猫吃鱼", result); assertEquals("猫吃鱼", result);
cat.seize(); cat.seize();
} }
@ -26,7 +26,7 @@ public class AopTest {
public void aopByAutoCglibTest() { public void aopByAutoCglibTest() {
Dog dog = ProxyUtil.proxy(new Dog(), TimeIntervalAspect.class); Dog dog = ProxyUtil.proxy(new Dog(), TimeIntervalAspect.class);
String result = dog.eat(); String result = dog.eat();
Assert.assertEquals("狗吃肉", result); assertEquals("狗吃肉", result);
dog.seize(); dog.seize();
} }
@ -78,7 +78,7 @@ public class AopTest {
TagObj proxy = ProxyUtil.proxy(target, TimeIntervalAspect.class); TagObj proxy = ProxyUtil.proxy(target, TimeIntervalAspect.class);
//代理类获取标记tag (断言错误) //代理类获取标记tag (断言错误)
Assert.assertEquals("tag", proxy.getTag()); assertEquals("tag", proxy.getTag());
} }
@Data @Data

View File

@ -19,7 +19,7 @@ import cn.hutool.aop.proxy.ProxyFactory;
import cn.hutool.aop.proxy.SpringCglibProxyFactory; import cn.hutool.aop.proxy.SpringCglibProxyFactory;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import lombok.Setter; import lombok.Setter;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class IssueI74EX7Test { public class IssueI74EX7Test {
@Test @Test

View File

@ -1,8 +1,8 @@
package cn.hutool.bloomfilter; package cn.hutool.bloomfilter;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import cn.hutool.bloomfilter.bitMap.IntMap; import cn.hutool.bloomfilter.bitMap.IntMap;
import cn.hutool.bloomfilter.bitMap.LongMap; import cn.hutool.bloomfilter.bitMap.LongMap;
@ -16,13 +16,13 @@ public class BitMapBloomFilterTest {
filter.add("abc"); filter.add("abc");
filter.add("ddd"); filter.add("ddd");
Assert.assertTrue(filter.contains("abc")); assertTrue(filter.contains("abc"));
Assert.assertTrue(filter.contains("ddd")); assertTrue(filter.contains("ddd"));
Assert.assertTrue(filter.contains("123")); assertTrue(filter.contains("123"));
} }
@Test @Test
@Ignore @Disabled
public void testIntMap(){ public void testIntMap(){
IntMap intMap = new IntMap(); IntMap intMap = new IntMap();
@ -38,7 +38,7 @@ public class BitMapBloomFilterTest {
} }
@Test @Test
@Ignore @Disabled
public void testLongMap(){ public void testLongMap(){
LongMap longMap = new LongMap(); LongMap longMap = new LongMap();

View File

@ -6,9 +6,9 @@ import cn.hutool.cache.impl.WeakCache;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ConcurrencyTester; import cn.hutool.core.thread.ConcurrencyTester;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -21,7 +21,7 @@ import java.util.concurrent.atomic.AtomicInteger;
public class CacheConcurrentTest { public class CacheConcurrentTest {
@Test @Test
@Ignore @Disabled
public void fifoCacheTest() { public void fifoCacheTest() {
int threadCount = 4000; int threadCount = 4000;
final Cache<String, String> cache = new FIFOCache<>(3); final Cache<String, String> cache = new FIFOCache<>(3);
@ -52,7 +52,7 @@ public class CacheConcurrentTest {
} }
@Test @Test
@Ignore @Disabled
public void lruCacheTest() { public void lruCacheTest() {
int threadCount = 40000; int threadCount = 40000;
final Cache<String, String> cache = new LRUCache<>(1000); final Cache<String, String> cache = new LRUCache<>(1000);
@ -102,6 +102,6 @@ public class CacheConcurrentTest {
}); });
long interval = concurrencyTester.getInterval(); long interval = concurrencyTester.getInterval();
// 总耗时应与单次操作耗时在同一个数量级 // 总耗时应与单次操作耗时在同一个数量级
Assert.assertTrue(interval < delay * 2); assertTrue(interval < delay * 2);
} }
} }

View File

@ -4,8 +4,8 @@ import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.date.DateUnit; import cn.hutool.core.date.DateUnit;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* 缓存测试用例 * 缓存测试用例
@ -19,8 +19,8 @@ public class CacheTest {
Cache<String,String> fifoCache = CacheUtil.newFIFOCache(3); Cache<String,String> fifoCache = CacheUtil.newFIFOCache(3);
fifoCache.setListener((key, value)->{ fifoCache.setListener((key, value)->{
// 监听测试此测试中只有key1被移除测试是否监听成功 // 监听测试此测试中只有key1被移除测试是否监听成功
Assert.assertEquals("key1", key); assertEquals("key1", key);
Assert.assertEquals("value1", value); assertEquals("value1", value);
}); });
fifoCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3); fifoCache.put("key1", "value1", DateUnit.SECOND.getMillis() * 3);
@ -30,7 +30,7 @@ public class CacheTest {
//由于缓存容量只有3当加入第四个元素的时候根据FIFO规则最先放入的对象将被移除 //由于缓存容量只有3当加入第四个元素的时候根据FIFO规则最先放入的对象将被移除
String value1 = fifoCache.get("key1"); String value1 = fifoCache.get("key1");
Assert.assertNull(value1); assertNull(value1);
} }
@Test @Test
@ -39,7 +39,7 @@ public class CacheTest {
for (int i = 0; i < RandomUtil.randomInt(100, 1000); i++) { for (int i = 0; i < RandomUtil.randomInt(100, 1000); i++) {
fifoCache.put("key" + i, "value" + i); fifoCache.put("key" + i, "value" + i);
} }
Assert.assertEquals(100, fifoCache.size()); assertEquals(100, fifoCache.size());
} }
@Test @Test
@ -56,16 +56,16 @@ public class CacheTest {
String value1 = lfuCache.get("key1"); String value1 = lfuCache.get("key1");
String value2 = lfuCache.get("key2"); String value2 = lfuCache.get("key2");
String value3 = lfuCache.get("key3"); String value3 = lfuCache.get("key3");
Assert.assertNotNull(value1); assertNotNull(value1);
Assert.assertNull(value2); assertNull(value2);
Assert.assertNull(value3); assertNull(value3);
} }
@Test @Test
public void lfuCacheTest2(){ public void lfuCacheTest2(){
Cache<String, String> lfuCache = CacheUtil.newLFUCache(3); Cache<String, String> lfuCache = CacheUtil.newLFUCache(3);
final String s = lfuCache.get(null); final String s = lfuCache.get(null);
Assert.assertNull(s); assertNull(s);
} }
@Test @Test
@ -81,10 +81,10 @@ public class CacheTest {
lruCache.put("key4", "value4", DateUnit.SECOND.getMillis() * 3); lruCache.put("key4", "value4", DateUnit.SECOND.getMillis() * 3);
String value1 = lruCache.get("key1"); String value1 = lruCache.get("key1");
Assert.assertNotNull(value1); assertNotNull(value1);
//由于缓存容量只有3当加入第四个元素的时候根据LRU规则最少使用的将被移除2被移除 //由于缓存容量只有3当加入第四个元素的时候根据LRU规则最少使用的将被移除2被移除
String value2 = lruCache.get("key2"); String value2 = lruCache.get("key2");
Assert.assertNull(value2); assertNull(value2);
} }
@Test @Test
@ -103,20 +103,20 @@ public class CacheTest {
//5毫秒后由于value2设置了5毫秒过期因此只有value2被保留下来 //5毫秒后由于value2设置了5毫秒过期因此只有value2被保留下来
String value1 = timedCache.get("key1"); String value1 = timedCache.get("key1");
Assert.assertNull(value1); assertNull(value1);
String value2 = timedCache.get("key2"); String value2 = timedCache.get("key2");
Assert.assertEquals("value2", value2); assertEquals("value2", value2);
//5毫秒后由于设置了默认过期key3只被保留4毫秒因此为null //5毫秒后由于设置了默认过期key3只被保留4毫秒因此为null
String value3 = timedCache.get("key3"); String value3 = timedCache.get("key3");
Assert.assertNull(value3); assertNull(value3);
String value3Supplier = timedCache.get("key3", () -> "Default supplier"); String value3Supplier = timedCache.get("key3", () -> "Default supplier");
Assert.assertEquals("Default supplier", value3Supplier); assertEquals("Default supplier", value3Supplier);
// 永不过期 // 永不过期
String value4 = timedCache.get("key4"); String value4 = timedCache.get("key4");
Assert.assertEquals("value4", value4); assertEquals("value4", value4);
//取消定时清理 //取消定时清理
timedCache.cancelPruneSchedule(); timedCache.cancelPruneSchedule();

View File

@ -1,7 +1,7 @@
package cn.hutool.cache; package cn.hutool.cache;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import cn.hutool.cache.file.LFUFileCache; import cn.hutool.cache.file.LFUFileCache;
@ -14,6 +14,6 @@ public class FileCacheTest {
@Test @Test
public void lfuFileCacheTest() { public void lfuFileCacheTest() {
LFUFileCache cache = new LFUFileCache(1000, 500, 2000); LFUFileCache cache = new LFUFileCache(1000, 500, 2000);
Assert.assertNotNull(cache); assertNotNull(cache);
} }
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.cache; package cn.hutool.cache;
import cn.hutool.cache.impl.FIFOCache; import cn.hutool.cache.impl.FIFOCache;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class Issue3618Test { public class Issue3618Test {
@Test @Test
@ -12,11 +12,11 @@ public class Issue3618Test {
cache.put(2, 1); cache.put(2, 1);
cache.put(3, 1); cache.put(3, 1);
Assert.assertEquals(3, cache.size()); assertEquals(3, cache.size());
// issue#3618 对于替换的键值对不做满队列检查和清除 // issue#3618 对于替换的键值对不做满队列检查和清除
cache.put(3, 2); cache.put(3, 2);
Assert.assertEquals(3, cache.size()); assertEquals(3, cache.size());
} }
} }

View File

@ -3,13 +3,13 @@ package cn.hutool.cache;
import cn.hutool.cache.impl.TimedCache; import cn.hutool.cache.impl.TimedCache;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class IssueI8MEIXTest { public class IssueI8MEIXTest {
@Test @Test
@Ignore @Disabled
public void getRemoveTest() { public void getRemoveTest() {
final TimedCache<String, String> cache = new TimedCache<>(200); final TimedCache<String, String> cache = new TimedCache<>(200);
cache.put("a", "123"); cache.put("a", "123");

View File

@ -4,9 +4,9 @@ import cn.hutool.cache.impl.LRUCache;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.concurrent.CountDownLatch; import java.util.concurrent.CountDownLatch;
import java.util.concurrent.atomic.AtomicInteger; import java.util.concurrent.atomic.AtomicInteger;
@ -19,7 +19,7 @@ import java.util.concurrent.atomic.AtomicInteger;
public class LRUCacheTest { public class LRUCacheTest {
@Test @Test
@Ignore @Disabled
public void putTest(){ public void putTest(){
//https://github.com/dromara/hutool/issues/2227 //https://github.com/dromara/hutool/issues/2227
final LRUCache<String, String> cache = CacheUtil.newLRUCache(100, 10); final LRUCache<String, String> cache = CacheUtil.newLRUCache(100, 10);
@ -55,7 +55,7 @@ public class LRUCacheTest {
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
sb1.append(cache.get(i)); sb1.append(cache.get(i));
} }
Assert.assertEquals("0123456789", sb1.toString()); assertEquals("0123456789", sb1.toString());
// 新加11此时0最久未使用应该淘汰0 // 新加11此时0最久未使用应该淘汰0
cache.put(11, 11); cache.put(11, 11);
@ -64,7 +64,7 @@ public class LRUCacheTest {
for (int i = 0; i < 10; i++) { for (int i = 0; i < 10; i++) {
sb2.append(cache.get(i)); sb2.append(cache.get(i));
} }
Assert.assertEquals("null123456789", sb2.toString()); assertEquals("null123456789", sb2.toString());
} }
@Test @Test
@ -82,7 +82,7 @@ public class LRUCacheTest {
cache.put(StrUtil.format("key-{}", i), i); cache.put(StrUtil.format("key-{}", i), i);
} }
Assert.assertEquals(7, removeCount.get()); assertEquals(7, removeCount.get());
Assert.assertEquals(3, cache.size()); assertEquals(3, cache.size());
} }
} }

View File

@ -2,9 +2,9 @@ package cn.hutool.cache;
import cn.hutool.cache.impl.WeakCache; import cn.hutool.cache.impl.WeakCache;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class WeakCacheTest { public class WeakCacheTest {
@ -14,16 +14,16 @@ public class WeakCacheTest {
cache.put("abc", "123"); cache.put("abc", "123");
cache.put("def", "456"); cache.put("def", "456");
Assert.assertEquals(2, cache.size()); assertEquals(2, cache.size());
// 检查被MutableObj包装的key能否正常移除 // 检查被MutableObj包装的key能否正常移除
cache.remove("abc"); cache.remove("abc");
Assert.assertEquals(1, cache.size()); assertEquals(1, cache.size());
} }
@Test @Test
@Ignore @Disabled
public void removeByGcTest(){ public void removeByGcTest(){
// https://gitee.com/dromara/hutool/issues/I51O7M // https://gitee.com/dromara/hutool/issues/I51O7M
WeakCache<String, String> cache = new WeakCache<>(-1); WeakCache<String, String> cache = new WeakCache<>(-1);
@ -31,7 +31,7 @@ public class WeakCacheTest {
cache.put("b", "2"); cache.put("b", "2");
// 监听 // 监听
Assert.assertEquals(2, cache.size()); assertEquals(2, cache.size());
cache.setListener(Console::log); cache.setListener(Console::log);
// GC测试 // GC测试

View File

@ -2,9 +2,9 @@ package cn.hutool.captcha;
import cn.hutool.captcha.generator.MathGenerator; import cn.hutool.captcha.generator.MathGenerator;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.awt.*; import java.awt.*;
@ -19,12 +19,12 @@ public class CaptchaTest {
public void lineCaptchaTest1() { public void lineCaptchaTest1() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100); LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 100);
Assert.assertNotNull(lineCaptcha.getCode()); assertNotNull(lineCaptcha.getCode());
Assert.assertTrue(lineCaptcha.verify(lineCaptcha.getCode())); assertTrue(lineCaptcha.verify(lineCaptcha.getCode()));
} }
@Test @Test
@Ignore @Disabled
public void lineCaptchaTest3() { public void lineCaptchaTest3() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 70, 4, 15); LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 70, 4, 15);
@ -33,7 +33,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void lineCaptchaTestWithSize() { public void lineCaptchaTestWithSize() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 70, 4, 15, 0.65f); LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 70, 4, 15, 0.65f);
@ -42,7 +42,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void lineCaptchaWithMathTest() { public void lineCaptchaWithMathTest() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 80); LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(200, 80);
@ -52,7 +52,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void lineCaptchaTest2() { public void lineCaptchaTest2() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
@ -72,7 +72,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void circleCaptchaTest() { public void circleCaptchaTest() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
@ -86,7 +86,7 @@ public class CaptchaTest {
@Test @Test
@Ignore @Disabled
public void circleCaptchaTestWithSize() { public void circleCaptchaTestWithSize() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 70, 4, 15, 0.65f); CircleCaptcha captcha = CaptchaUtil.createCircleCaptcha(200, 70, 4, 15, 0.65f);
@ -95,7 +95,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void shearCaptchaTest() { public void shearCaptchaTest() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
@ -108,7 +108,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void shearCaptchaTest2() { public void shearCaptchaTest2() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
@ -120,7 +120,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void ShearCaptchaWithMathTest() { public void ShearCaptchaWithMathTest() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4); ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 45, 4, 4);
@ -134,7 +134,7 @@ public class CaptchaTest {
@Test @Test
@Ignore @Disabled
public void ShearCaptchaTestWithSize() { public void ShearCaptchaTestWithSize() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 70, 4, 15, 0.65f); ShearCaptcha captcha = CaptchaUtil.createShearCaptcha(200, 70, 4, 15, 0.65f);
@ -143,7 +143,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void GifCaptchaTest() { public void GifCaptchaTest() {
GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 100, 4); GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 100, 4);
captcha.write("d:/test/gif_captcha.gif"); captcha.write("d:/test/gif_captcha.gif");
@ -151,7 +151,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void GifCaptchaTestWithSize() { public void GifCaptchaTestWithSize() {
// 定义图形验证码的长和宽 // 定义图形验证码的长和宽
GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 70, 4, 15, 0.65f); GifCaptcha captcha = CaptchaUtil.createGifCaptcha(200, 70, 4, 15, 0.65f);
@ -160,7 +160,7 @@ public class CaptchaTest {
} }
@Test @Test
@Ignore @Disabled
public void bgTest() { public void bgTest() {
LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 1); LineCaptcha captcha = CaptchaUtil.createLineCaptcha(200, 100, 4, 1);
captcha.setBackground(Color.WHITE); captcha.setBackground(Color.WHITE);

View File

@ -4,8 +4,8 @@ import cn.hutool.core.img.GraphicsUtil;
import cn.hutool.core.img.ImgUtil; import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.awt.Color; import java.awt.Color;
import java.awt.Graphics; import java.awt.Graphics;
@ -17,7 +17,7 @@ import java.util.concurrent.ThreadLocalRandom;
public class CaptchaUtilTest { public class CaptchaUtilTest {
@Test @Test
@Ignore @Disabled
public void createTest() { public void createTest() {
for(int i = 0; i < 1; i++) { for(int i = 0; i < 1; i++) {
CaptchaUtil.createShearCaptcha(320, 240); CaptchaUtil.createShearCaptcha(320, 240);
@ -25,7 +25,7 @@ public class CaptchaUtilTest {
} }
@Test @Test
@Ignore @Disabled
public void drawStringColourfulColorDistanceTest() { public void drawStringColourfulColorDistanceTest() {
for(int i = 0; i < 10; i++) { for(int i = 0; i < 10; i++) {
AbstractCaptcha lineCaptcha = new TestLineCaptchaColorDistance(200, 100, 5, 10); AbstractCaptcha lineCaptcha = new TestLineCaptchaColorDistance(200, 100, 5, 10);
@ -34,7 +34,7 @@ public class CaptchaUtilTest {
} }
@Test @Test
@Ignore @Disabled
public void drawStringColourfulDefaultColorDistanceTest() { public void drawStringColourfulDefaultColorDistanceTest() {
for(int i = 0; i < 10; i++) { for(int i = 0; i < 10; i++) {
AbstractCaptcha lineCaptcha = new TestLineCaptchaColorDistanceDefaultColorDistance(200, 100, 5, 10); AbstractCaptcha lineCaptcha = new TestLineCaptchaColorDistanceDefaultColorDistance(200, 100, 5, 10);

View File

@ -1,7 +1,7 @@
package cn.hutool.captcha; package cn.hutool.captcha;
import cn.hutool.captcha.generator.MathGenerator; import cn.hutool.captcha.generator.MathGenerator;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class GeneratorTest { public class GeneratorTest {

View File

@ -29,9 +29,9 @@ public class AnnotationProxy<T extends Annotation> implements Annotation, Invoca
* *
* @param annotation 注解 * @param annotation 注解
*/ */
@SuppressWarnings("unchecked")
public AnnotationProxy(T annotation) { public AnnotationProxy(T annotation) {
this.annotation = annotation; this.annotation = annotation;
//noinspection unchecked
this.type = (Class<T>) annotation.annotationType(); this.type = (Class<T>) annotation.annotationType();
this.attributes = initAttributes(); this.attributes = initAttributes();
} }

View File

@ -128,13 +128,13 @@ public class AnnotationUtil {
* @return 注解对象数组 * @return 注解对象数组
* @since 5.8.0 * @since 5.8.0
*/ */
@SuppressWarnings("unchecked")
public static <T> T[] getAnnotations(AnnotatedElement annotationEle, boolean isToCombination, Class<T> annotationType) { public static <T> T[] getAnnotations(AnnotatedElement annotationEle, boolean isToCombination, Class<T> annotationType) {
final Annotation[] annotations = getAnnotations(annotationEle, isToCombination, final Annotation[] annotations = getAnnotations(annotationEle, isToCombination,
(annotation -> null == annotationType || annotationType.isAssignableFrom(annotation.getClass()))); (annotation -> null == annotationType || annotationType.isAssignableFrom(annotation.getClass())));
final T[] result = ArrayUtil.newArray(annotationType, annotations.length); final T[] result = ArrayUtil.newArray(annotationType, annotations.length);
for (int i = 0; i < annotations.length; i++) { for (int i = 0; i < annotations.length; i++) {
//noinspection unchecked
result[i] = (T) annotations[i]; result[i] = (T) annotations[i];
} }
return result; return result;

View File

@ -27,24 +27,24 @@ public class LambdaUtil {
* <li>引用特定对象的实例方法<pre>{@code * <li>引用特定对象的实例方法<pre>{@code
* MyTeacher myTeacher = new MyTeacher(); * MyTeacher myTeacher = new MyTeacher();
* Class<MyTeacher> supplierClass = LambdaUtil.getRealClass(myTeacher::getAge); * Class<MyTeacher> supplierClass = LambdaUtil.getRealClass(myTeacher::getAge);
* Assert.assertEquals(MyTeacher.class, supplierClass); * assertEquals(MyTeacher.class, supplierClass);
* }</pre></li> * }</pre></li>
* <li>引用静态无参方法<pre>{@code * <li>引用静态无参方法<pre>{@code
* Class<MyTeacher> staticSupplierClass = LambdaUtil.getRealClass(MyTeacher::takeAge); * Class<MyTeacher> staticSupplierClass = LambdaUtil.getRealClass(MyTeacher::takeAge);
* Assert.assertEquals(MyTeacher.class, staticSupplierClass); * assertEquals(MyTeacher.class, staticSupplierClass);
* }</pre></li> * }</pre></li>
* </ul> * </ul>
* 在以下场景无法获取到正确类型 * 在以下场景无法获取到正确类型
* <pre>{@code * <pre>{@code
* // 枚举测试只能获取到枚举类型 * // 枚举测试只能获取到枚举类型
* Class<Enum<?>> enumSupplierClass = LambdaUtil.getRealClass(LambdaUtil.LambdaKindEnum.REF_NONE::ordinal); * Class<Enum<?>> enumSupplierClass = LambdaUtil.getRealClass(LambdaUtil.LambdaKindEnum.REF_NONE::ordinal);
* Assert.assertEquals(Enum.class, enumSupplierClass); * assertEquals(Enum.class, enumSupplierClass);
* // 调用父类方法只能获取到父类类型 * // 调用父类方法只能获取到父类类型
* Class<Entity<?>> superSupplierClass = LambdaUtil.getRealClass(myTeacher::getId); * Class<Entity<?>> superSupplierClass = LambdaUtil.getRealClass(myTeacher::getId);
* Assert.assertEquals(Entity.class, superSupplierClass); * assertEquals(Entity.class, superSupplierClass);
* // 引用父类静态带参方法只能获取到父类类型 * // 引用父类静态带参方法只能获取到父类类型
* Class<Entity<?>> staticSuperFunctionClass = LambdaUtil.getRealClass(MyTeacher::takeId); * Class<Entity<?>> staticSuperFunctionClass = LambdaUtil.getRealClass(MyTeacher::takeId);
* Assert.assertEquals(Entity.class, staticSuperFunctionClass); * assertEquals(Entity.class, staticSuperFunctionClass);
* }</pre> * }</pre>
* *
* @param func lambda * @param func lambda
@ -114,11 +114,11 @@ public class LambdaUtil {
* <ul> * <ul>
* <li>引用特定类型的任意对象的实例方法<pre>{@code * <li>引用特定类型的任意对象的实例方法<pre>{@code
* Class<MyTeacher> functionClass = LambdaUtil.getRealClass(MyTeacher::getAge); * Class<MyTeacher> functionClass = LambdaUtil.getRealClass(MyTeacher::getAge);
* Assert.assertEquals(MyTeacher.class, functionClass); * assertEquals(MyTeacher.class, functionClass);
* }</pre></li> * }</pre></li>
* <li>引用静态带参方法<pre>{@code * <li>引用静态带参方法<pre>{@code
* Class<MyTeacher> staticFunctionClass = LambdaUtil.getRealClass(MyTeacher::takeAgeBy); * Class<MyTeacher> staticFunctionClass = LambdaUtil.getRealClass(MyTeacher::takeAgeBy);
* Assert.assertEquals(MyTeacher.class, staticFunctionClass); * assertEquals(MyTeacher.class, staticFunctionClass);
* }</pre></li> * }</pre></li>
* </ul> * </ul>
* *

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -19,19 +19,19 @@ public class AbstractWrappedAnnotationAttributeTest {
CacheableAnnotationAttribute nameAttribute = new CacheableAnnotationAttribute(annotation, nameMethod); CacheableAnnotationAttribute nameAttribute = new CacheableAnnotationAttribute(annotation, nameMethod);
AbstractWrappedAnnotationAttribute nameWrapper = new TestWrappedAnnotationAttribute(nameAttribute, valueAttribute); AbstractWrappedAnnotationAttribute nameWrapper = new TestWrappedAnnotationAttribute(nameAttribute, valueAttribute);
Assert.assertEquals(nameWrapper.getAnnotation(), annotation); assertEquals(nameWrapper.getAnnotation(), annotation);
// 注解属性 // 注解属性
Assert.assertEquals(annotation, nameWrapper.getAnnotation()); assertEquals(annotation, nameWrapper.getAnnotation());
Assert.assertEquals(annotation.annotationType(), nameWrapper.getAnnotationType()); assertEquals(annotation.annotationType(), nameWrapper.getAnnotationType());
Assert.assertEquals(nameAttribute, nameWrapper.getOriginal()); assertEquals(nameAttribute, nameWrapper.getOriginal());
Assert.assertEquals(valueAttribute, nameWrapper.getLinked()); assertEquals(valueAttribute, nameWrapper.getLinked());
// 方法属性 // 方法属性
Assert.assertEquals(nameMethod.getName(), nameWrapper.getAttributeName()); assertEquals(nameMethod.getName(), nameWrapper.getAttributeName());
Assert.assertEquals(nameMethod.getReturnType(), nameWrapper.getAttributeType()); assertEquals(nameMethod.getReturnType(), nameWrapper.getAttributeType());
Assert.assertTrue(nameWrapper.isWrapped()); assertTrue(nameWrapper.isWrapped());
Assert.assertEquals("value1", nameWrapper.getValue()); assertEquals("value1", nameWrapper.getValue());
} }
@Test @Test
@ -43,24 +43,24 @@ public class AbstractWrappedAnnotationAttributeTest {
Method name1Method = ReflectUtil.getMethod(AnnotationForTest1.class, "name1"); Method name1Method = ReflectUtil.getMethod(AnnotationForTest1.class, "name1");
CacheableAnnotationAttribute name1Attribute = new CacheableAnnotationAttribute(annotation1, name1Method); CacheableAnnotationAttribute name1Attribute = new CacheableAnnotationAttribute(annotation1, name1Method);
AbstractWrappedAnnotationAttribute wrapper1 = new TestWrappedAnnotationAttribute(name1Attribute, value1Attribute); AbstractWrappedAnnotationAttribute wrapper1 = new TestWrappedAnnotationAttribute(name1Attribute, value1Attribute);
Assert.assertEquals(name1Attribute, wrapper1.getNonWrappedOriginal()); assertEquals(name1Attribute, wrapper1.getNonWrappedOriginal());
Assert.assertEquals(CollUtil.newArrayList(name1Attribute, value1Attribute), wrapper1.getAllLinkedNonWrappedAttributes()); assertEquals(CollUtil.newArrayList(name1Attribute, value1Attribute), wrapper1.getAllLinkedNonWrappedAttributes());
// 包装第二层( name1 + value1 ) + value2 // 包装第二层( name1 + value1 ) + value2
Annotation annotation2 = ClassForTest1.class.getAnnotation(AnnotationForTest2.class); Annotation annotation2 = ClassForTest1.class.getAnnotation(AnnotationForTest2.class);
Method value2Method = ReflectUtil.getMethod(AnnotationForTest2.class, "value2"); Method value2Method = ReflectUtil.getMethod(AnnotationForTest2.class, "value2");
CacheableAnnotationAttribute value2Attribute = new CacheableAnnotationAttribute(annotation2, value2Method); CacheableAnnotationAttribute value2Attribute = new CacheableAnnotationAttribute(annotation2, value2Method);
AbstractWrappedAnnotationAttribute wrapper2 = new TestWrappedAnnotationAttribute(wrapper1, value2Attribute); AbstractWrappedAnnotationAttribute wrapper2 = new TestWrappedAnnotationAttribute(wrapper1, value2Attribute);
Assert.assertEquals(name1Attribute, wrapper2.getNonWrappedOriginal()); assertEquals(name1Attribute, wrapper2.getNonWrappedOriginal());
Assert.assertEquals(CollUtil.newArrayList(name1Attribute, value1Attribute, value2Attribute), wrapper2.getAllLinkedNonWrappedAttributes()); assertEquals(CollUtil.newArrayList(name1Attribute, value1Attribute, value2Attribute), wrapper2.getAllLinkedNonWrappedAttributes());
// 包装第二层value3 + ( ( name1 + value1 ) + value2 ) // 包装第二层value3 + ( ( name1 + value1 ) + value2 )
Annotation annotation3 = ClassForTest1.class.getAnnotation(AnnotationForTest3.class); Annotation annotation3 = ClassForTest1.class.getAnnotation(AnnotationForTest3.class);
Method value3Method = ReflectUtil.getMethod(AnnotationForTest3.class, "value3"); Method value3Method = ReflectUtil.getMethod(AnnotationForTest3.class, "value3");
CacheableAnnotationAttribute value3Attribute = new CacheableAnnotationAttribute(annotation3, value3Method); CacheableAnnotationAttribute value3Attribute = new CacheableAnnotationAttribute(annotation3, value3Method);
AbstractWrappedAnnotationAttribute wrapper3 = new TestWrappedAnnotationAttribute(value3Attribute, wrapper2); AbstractWrappedAnnotationAttribute wrapper3 = new TestWrappedAnnotationAttribute(value3Attribute, wrapper2);
Assert.assertEquals(value3Attribute, wrapper3.getNonWrappedOriginal()); assertEquals(value3Attribute, wrapper3.getNonWrappedOriginal());
Assert.assertEquals(CollUtil.newArrayList(value3Attribute, name1Attribute, value1Attribute, value2Attribute), wrapper3.getAllLinkedNonWrappedAttributes()); assertEquals(CollUtil.newArrayList(value3Attribute, name1Attribute, value1Attribute, value2Attribute), wrapper3.getAllLinkedNonWrappedAttributes());
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -26,16 +26,16 @@ public class AliasAnnotationPostProcessorTest {
processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator); processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator);
AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value"); AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value"), valueAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value"), valueAttribute.getAttribute());
Assert.assertTrue(valueAttribute.isWrapped()); assertTrue(valueAttribute.isWrapped());
Assert.assertEquals(ForceAliasedAnnotationAttribute.class, valueAttribute.getClass()); assertEquals(ForceAliasedAnnotationAttribute.class, valueAttribute.getClass());
AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name"); AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name"), nameAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name"), nameAttribute.getAttribute());
Assert.assertFalse(nameAttribute.isWrapped()); assertFalse(nameAttribute.isWrapped());
Assert.assertEquals(CacheableAnnotationAttribute.class, nameAttribute.getClass()); assertEquals(CacheableAnnotationAttribute.class, nameAttribute.getClass());
Assert.assertEquals(nameAttribute, ((WrappedAnnotationAttribute)valueAttribute).getLinked()); assertEquals(nameAttribute, ((WrappedAnnotationAttribute)valueAttribute).getLinked());
} }
@AnnotationForTest @AnnotationForTest

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -26,16 +26,16 @@ public class AliasLinkAnnotationPostProcessorTest {
processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator); processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator);
AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value"); AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value"), valueAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value"), valueAttribute.getAttribute());
Assert.assertFalse(valueAttribute.isWrapped()); assertFalse(valueAttribute.isWrapped());
Assert.assertEquals(CacheableAnnotationAttribute.class, valueAttribute.getClass()); assertEquals(CacheableAnnotationAttribute.class, valueAttribute.getClass());
AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name"); AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name"), nameAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name"), nameAttribute.getAttribute());
Assert.assertTrue(nameAttribute.isWrapped()); assertTrue(nameAttribute.isWrapped());
Assert.assertEquals(ForceAliasedAnnotationAttribute.class, nameAttribute.getClass()); assertEquals(ForceAliasedAnnotationAttribute.class, nameAttribute.getClass());
Assert.assertEquals(valueAttribute, ((WrappedAnnotationAttribute)nameAttribute).getLinked()); assertEquals(valueAttribute, ((WrappedAnnotationAttribute)nameAttribute).getLinked());
} }
@Test @Test
@ -50,16 +50,16 @@ public class AliasLinkAnnotationPostProcessorTest {
processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator); processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator);
AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value2"); AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value2");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value2"), valueAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value2"), valueAttribute.getAttribute());
Assert.assertFalse(valueAttribute.isWrapped()); assertFalse(valueAttribute.isWrapped());
Assert.assertEquals(CacheableAnnotationAttribute.class, valueAttribute.getClass()); assertEquals(CacheableAnnotationAttribute.class, valueAttribute.getClass());
AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name2"); AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name2");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name2"), nameAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name2"), nameAttribute.getAttribute());
Assert.assertTrue(nameAttribute.isWrapped()); assertTrue(nameAttribute.isWrapped());
Assert.assertEquals(AliasedAnnotationAttribute.class, nameAttribute.getClass()); assertEquals(AliasedAnnotationAttribute.class, nameAttribute.getClass());
Assert.assertEquals(valueAttribute, ((WrappedAnnotationAttribute)nameAttribute).getLinked()); assertEquals(valueAttribute, ((WrappedAnnotationAttribute)nameAttribute).getLinked());
} }
@AnnotationForTest @AnnotationForTest

View File

@ -1,8 +1,8 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -20,13 +20,13 @@ public class AliasedAnnotationAttributeTest {
final AliasedAnnotationAttribute valueAnnotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute); final AliasedAnnotationAttribute valueAnnotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute);
// 注解属性 // 注解属性
Assert.assertEquals(annotation, valueAnnotationAttribute.getAnnotation()); assertEquals(annotation, valueAnnotationAttribute.getAnnotation());
Assert.assertEquals(annotation.annotationType(), valueAnnotationAttribute.getAnnotationType()); assertEquals(annotation.annotationType(), valueAnnotationAttribute.getAnnotationType());
// 方法属性 // 方法属性
Assert.assertEquals(valueMethod.getAnnotation(Alias.class), valueAnnotationAttribute.getAnnotation(Alias.class)); assertEquals(valueMethod.getAnnotation(Alias.class), valueAnnotationAttribute.getAnnotation(Alias.class));
Assert.assertEquals(valueMethod.getName(), valueAnnotationAttribute.getAttributeName()); assertEquals(valueMethod.getName(), valueAnnotationAttribute.getAttributeName());
Assert.assertEquals(nameMethod.getReturnType(), valueAnnotationAttribute.getAttributeType()); assertEquals(nameMethod.getReturnType(), valueAnnotationAttribute.getAttributeType());
} }
@Test @Test
@ -40,9 +40,9 @@ public class AliasedAnnotationAttributeTest {
final AliasedAnnotationAttribute annotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute); final AliasedAnnotationAttribute annotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute);
// 值处理 // 值处理
Assert.assertEquals("name", annotationAttribute.getValue()); assertEquals("name", annotationAttribute.getValue());
Assert.assertFalse(annotationAttribute.isValueEquivalentToDefaultValue()); assertFalse(annotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertTrue(annotationAttribute.isWrapped()); assertTrue(annotationAttribute.isWrapped());
} }
@Test @Test
@ -56,9 +56,9 @@ public class AliasedAnnotationAttributeTest {
final AliasedAnnotationAttribute annotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute); final AliasedAnnotationAttribute annotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute);
// 值处理 // 值处理
Assert.assertEquals("value", annotationAttribute.getValue()); assertEquals("value", annotationAttribute.getValue());
Assert.assertFalse(annotationAttribute.isValueEquivalentToDefaultValue()); assertFalse(annotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertTrue(annotationAttribute.isWrapped()); assertTrue(annotationAttribute.isWrapped());
} }
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
@ -20,41 +20,41 @@ public class AnnotationUtilTest {
@Test @Test
public void getCombinationAnnotationsTest(){ public void getCombinationAnnotationsTest(){
final Annotation[] annotations = AnnotationUtil.getAnnotations(ClassWithAnnotation.class, true); final Annotation[] annotations = AnnotationUtil.getAnnotations(ClassWithAnnotation.class, true);
Assert.assertNotNull(annotations); assertNotNull(annotations);
Assert.assertEquals(2, annotations.length); assertEquals(2, annotations.length);
} }
@Test @Test
public void getCombinationAnnotationsWithClassTest(){ public void getCombinationAnnotationsWithClassTest(){
final AnnotationForTest[] annotations = AnnotationUtil.getCombinationAnnotations(ClassWithAnnotation.class, AnnotationForTest.class); final AnnotationForTest[] annotations = AnnotationUtil.getCombinationAnnotations(ClassWithAnnotation.class, AnnotationForTest.class);
Assert.assertNotNull(annotations); assertNotNull(annotations);
Assert.assertEquals(1, annotations.length); assertEquals(1, annotations.length);
Assert.assertTrue(annotations[0].value().equals("测试") || annotations[0].value().equals("repeat-annotation")); assertTrue(annotations[0].value().equals("测试") || annotations[0].value().equals("repeat-annotation"));
} }
@Test @Test
public void getAnnotationValueTest() { public void getAnnotationValueTest() {
final Object value = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest.class); final Object value = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest.class);
Assert.assertTrue(value.equals("测试") || value.equals("repeat-annotation")); assertTrue(value.equals("测试") || value.equals("repeat-annotation"));
} }
@Test @Test
public void getAnnotationValueTest2() { public void getAnnotationValueTest2() {
final String[] names = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest::names); final String[] names = AnnotationUtil.getAnnotationValue(ClassWithAnnotation.class, AnnotationForTest::names);
Assert.assertTrue(names.length == 1 && names[0].isEmpty() || ArrayUtil.equals(names, new String[]{"测试1", "测试2"})); assertTrue(names.length == 1 && names[0].isEmpty() || ArrayUtil.equals(names, new String[]{"测试1", "测试2"}));
} }
@Test @Test
public void getAnnotationSyncAlias() { public void getAnnotationSyncAlias() {
// 直接获取 // 直接获取
Assert.assertEquals("", ClassWithAnnotation.class.getAnnotation(AnnotationForTest.class).retry()); assertEquals("", ClassWithAnnotation.class.getAnnotation(AnnotationForTest.class).retry());
// 加别名适配 // 加别名适配
final AnnotationForTest annotation = AnnotationUtil.getAnnotationAlias(ClassWithAnnotation.class, AnnotationForTest.class); final AnnotationForTest annotation = AnnotationUtil.getAnnotationAlias(ClassWithAnnotation.class, AnnotationForTest.class);
String retryValue = annotation.retry(); String retryValue = annotation.retry();
Assert.assertTrue(retryValue.equals("测试") || retryValue.equals("repeat-annotation")); assertTrue(retryValue.equals("测试") || retryValue.equals("repeat-annotation"));
Assert.assertTrue(AnnotationUtil.isSynthesizedAnnotation(annotation)); assertTrue(AnnotationUtil.isSynthesizedAnnotation(annotation));
} }
@Test @Test
@ -62,7 +62,7 @@ public class AnnotationUtilTest {
getAnnotationSyncAlias(); getAnnotationSyncAlias();
// 使用AnnotationUtil.getAnnotationAlias获取对象上并不存在的注解 // 使用AnnotationUtil.getAnnotationAlias获取对象上并不存在的注解
final Alias alias = AnnotationUtil.getAnnotationAlias(ClassWithAnnotation.class, Alias.class); final Alias alias = AnnotationUtil.getAnnotationAlias(ClassWithAnnotation.class, Alias.class);
Assert.assertNull(alias); assertNull(alias);
} }
@AnnotationForTest(value = "测试", names = {"测试1", "测试2"}) @AnnotationForTest(value = "测试", names = {"测试1", "测试2"})
@ -78,14 +78,14 @@ public class AnnotationUtilTest {
// RootAnnotation -> RootMetaAnnotation1 -> RootMetaAnnotation2 -> RootMetaAnnotation3 // RootAnnotation -> RootMetaAnnotation1 -> RootMetaAnnotation2 -> RootMetaAnnotation3
// -> RootMetaAnnotation3 // -> RootMetaAnnotation3
final List<Annotation> annotations = AnnotationUtil.scanMetaAnnotation(RootAnnotation.class); final List<Annotation> annotations = AnnotationUtil.scanMetaAnnotation(RootAnnotation.class);
Assert.assertEquals(4, annotations.size()); assertEquals(4, annotations.size());
Assert.assertTrue(annotations.get(0).annotationType() == RootMetaAnnotation3.class || assertTrue(annotations.get(0).annotationType() == RootMetaAnnotation3.class ||
annotations.get(0).annotationType() == RootMetaAnnotation1.class); annotations.get(0).annotationType() == RootMetaAnnotation1.class);
Assert.assertTrue(annotations.get(1).annotationType() == RootMetaAnnotation1.class || assertTrue(annotations.get(1).annotationType() == RootMetaAnnotation1.class ||
annotations.get(1).annotationType() == RootMetaAnnotation2.class); annotations.get(1).annotationType() == RootMetaAnnotation2.class);
Assert.assertTrue(annotations.get(2).annotationType() == RootMetaAnnotation2.class || assertTrue(annotations.get(2).annotationType() == RootMetaAnnotation2.class ||
annotations.get(2).annotationType() == RootMetaAnnotation3.class); annotations.get(2).annotationType() == RootMetaAnnotation3.class);
Assert.assertEquals(RootMetaAnnotation3.class, annotations.get(3).annotationType()); assertEquals(RootMetaAnnotation3.class, annotations.get(3).annotationType());
} }
@Test @Test
@ -93,12 +93,12 @@ public class AnnotationUtilTest {
// TargetClass -> TargetSuperClass ----------------------------------> SuperInterface // TargetClass -> TargetSuperClass ----------------------------------> SuperInterface
// -> TargetSuperInterface -> SuperTargetSuperInterface -> SuperInterface // -> TargetSuperInterface -> SuperTargetSuperInterface -> SuperInterface
final List<Annotation> annotations = AnnotationUtil.scanClass(TargetClass.class); final List<Annotation> annotations = AnnotationUtil.scanClass(TargetClass.class);
Assert.assertEquals(5, annotations.size()); assertEquals(5, annotations.size());
Assert.assertEquals("TargetClass", ((AnnotationForTest)annotations.get(0)).value()); assertEquals("TargetClass", ((AnnotationForTest)annotations.get(0)).value());
Assert.assertEquals("TargetSuperClass", ((AnnotationForTest)annotations.get(1)).value()); assertEquals("TargetSuperClass", ((AnnotationForTest)annotations.get(1)).value());
Assert.assertEquals("TargetSuperInterface", ((AnnotationForTest)annotations.get(2)).value()); assertEquals("TargetSuperInterface", ((AnnotationForTest)annotations.get(2)).value());
Assert.assertEquals("SuperInterface", ((AnnotationForTest)annotations.get(3)).value()); assertEquals("SuperInterface", ((AnnotationForTest)annotations.get(3)).value());
Assert.assertEquals("SuperTargetSuperInterface", ((AnnotationForTest)annotations.get(4)).value()); assertEquals("SuperTargetSuperInterface", ((AnnotationForTest)annotations.get(4)).value());
} }
@Test @Test
@ -106,12 +106,12 @@ public class AnnotationUtilTest {
// TargetClass -> TargetSuperClass // TargetClass -> TargetSuperClass
// -> TargetSuperInterface // -> TargetSuperInterface
final Method method = ReflectUtil.getMethod(TargetClass.class, "testMethod"); final Method method = ReflectUtil.getMethod(TargetClass.class, "testMethod");
Assert.assertNotNull(method); assertNotNull(method);
final List<Annotation> annotations = AnnotationUtil.scanMethod(method); final List<Annotation> annotations = AnnotationUtil.scanMethod(method);
Assert.assertEquals(3, annotations.size()); assertEquals(3, annotations.size());
Assert.assertEquals("TargetClass", ((AnnotationForTest)annotations.get(0)).value()); assertEquals("TargetClass", ((AnnotationForTest)annotations.get(0)).value());
Assert.assertEquals("TargetSuperClass", ((AnnotationForTest)annotations.get(1)).value()); assertEquals("TargetSuperClass", ((AnnotationForTest)annotations.get(1)).value());
Assert.assertEquals("TargetSuperInterface", ((AnnotationForTest)annotations.get(2)).value()); assertEquals("TargetSuperInterface", ((AnnotationForTest)annotations.get(2)).value());
} }
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -1,8 +1,8 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -15,11 +15,11 @@ public class CacheableAnnotationAttributeTest {
final Method attribute = ReflectUtil.getMethod(AnnotationForTest.class, "value"); final Method attribute = ReflectUtil.getMethod(AnnotationForTest.class, "value");
final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attribute); final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attribute);
// 注解属性 // 注解属性
Assert.assertEquals(annotation, annotationAttribute.getAnnotation()); assertEquals(annotation, annotationAttribute.getAnnotation());
Assert.assertEquals(annotation.annotationType(), annotationAttribute.getAnnotationType()); assertEquals(annotation.annotationType(), annotationAttribute.getAnnotationType());
// 方法属性 // 方法属性
Assert.assertEquals(attribute.getName(), annotationAttribute.getAttributeName()); assertEquals(attribute.getName(), annotationAttribute.getAttributeName());
Assert.assertEquals(attribute.getReturnType(), annotationAttribute.getAttributeType()); assertEquals(attribute.getReturnType(), annotationAttribute.getAttributeType());
} }
@Test @Test
@ -29,9 +29,9 @@ public class CacheableAnnotationAttributeTest {
final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attribute); final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attribute);
// 值处理 // 值处理
Assert.assertEquals("", annotationAttribute.getValue()); assertEquals("", annotationAttribute.getValue());
Assert.assertTrue(annotationAttribute.isValueEquivalentToDefaultValue()); assertTrue(annotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertFalse(annotationAttribute.isWrapped()); assertFalse(annotationAttribute.isWrapped());
} }
@Test @Test
@ -41,9 +41,9 @@ public class CacheableAnnotationAttributeTest {
final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attribute); final CacheableAnnotationAttribute annotationAttribute = new CacheableAnnotationAttribute(annotation, attribute);
// 值处理 // 值处理
Assert.assertEquals("test", annotationAttribute.getValue()); assertEquals("test", annotationAttribute.getValue());
Assert.assertFalse(annotationAttribute.isValueEquivalentToDefaultValue()); assertFalse(annotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertFalse(annotationAttribute.isWrapped()); assertFalse(annotationAttribute.isWrapped());
} }
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -3,8 +3,8 @@ package cn.hutool.core.annotation;
import cn.hutool.core.lang.Opt; import cn.hutool.core.lang.Opt;
import cn.hutool.core.map.MapBuilder; import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ClassUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.Arrays; import java.util.Arrays;
@ -22,8 +22,8 @@ public class CacheableSynthesizedAnnotationAttributeProcessorTest {
Map<String, Object> values2 = MapBuilder.<String, Object> create().put("name", "name2").put("value", "value2").build(); Map<String, Object> values2 = MapBuilder.<String, Object> create().put("name", "name2").put("value", "value2").build();
SynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0, values2); SynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0, values2);
Assert.assertEquals("name2", processor.getAttributeValue("name", String.class, Arrays.asList(annotation1, annotation2))); assertEquals("name2", processor.getAttributeValue("name", String.class, Arrays.asList(annotation1, annotation2)));
Assert.assertEquals(Integer.valueOf(111), processor.getAttributeValue("value", Integer.class, Arrays.asList(annotation1, annotation2))); assertEquals(Integer.valueOf(111), processor.getAttributeValue("value", Integer.class, Arrays.asList(annotation1, annotation2)));
} }
static class TestSynthesizedAnnotation implements SynthesizedAnnotation { static class TestSynthesizedAnnotation implements SynthesizedAnnotation {

View File

@ -1,8 +1,8 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -20,12 +20,12 @@ public class ForceAliasedAnnotationAttributeTest {
final ForceAliasedAnnotationAttribute valueAnnotationAttribute = new ForceAliasedAnnotationAttribute(valueAttribute, nameAttribute); final ForceAliasedAnnotationAttribute valueAnnotationAttribute = new ForceAliasedAnnotationAttribute(valueAttribute, nameAttribute);
// 注解属性 // 注解属性
Assert.assertEquals(annotation, valueAnnotationAttribute.getAnnotation()); assertEquals(annotation, valueAnnotationAttribute.getAnnotation());
Assert.assertEquals(annotation.annotationType(), valueAnnotationAttribute.getAnnotationType()); assertEquals(annotation.annotationType(), valueAnnotationAttribute.getAnnotationType());
// 方法属性 // 方法属性
Assert.assertEquals(valueMethod.getName(), valueAnnotationAttribute.getAttributeName()); assertEquals(valueMethod.getName(), valueAnnotationAttribute.getAttributeName());
Assert.assertEquals(valueMethod.getReturnType(), valueAnnotationAttribute.getAttributeType()); assertEquals(valueMethod.getReturnType(), valueAnnotationAttribute.getAttributeType());
} }
@Test @Test
@ -39,9 +39,9 @@ public class ForceAliasedAnnotationAttributeTest {
final AliasedAnnotationAttribute valueAnnotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute); final AliasedAnnotationAttribute valueAnnotationAttribute = new AliasedAnnotationAttribute(valueAttribute, nameAttribute);
// 值处理 // 值处理
Assert.assertEquals("name", valueAnnotationAttribute.getValue()); assertEquals("name", valueAnnotationAttribute.getValue());
Assert.assertFalse(valueAnnotationAttribute.isValueEquivalentToDefaultValue()); assertFalse(valueAnnotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertTrue(valueAnnotationAttribute.isWrapped()); assertTrue(valueAnnotationAttribute.isWrapped());
} }
@Test @Test
@ -55,9 +55,9 @@ public class ForceAliasedAnnotationAttributeTest {
final ForceAliasedAnnotationAttribute valueAnnotationAttribute = new ForceAliasedAnnotationAttribute(valueAttribute, nameAttribute); final ForceAliasedAnnotationAttribute valueAnnotationAttribute = new ForceAliasedAnnotationAttribute(valueAttribute, nameAttribute);
// 值处理 // 值处理
Assert.assertEquals("", valueAnnotationAttribute.getValue()); assertEquals("", valueAnnotationAttribute.getValue());
Assert.assertTrue(valueAnnotationAttribute.isValueEquivalentToDefaultValue()); assertTrue(valueAnnotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertTrue(valueAnnotationAttribute.isWrapped()); assertTrue(valueAnnotationAttribute.isWrapped());
} }
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -1,19 +1,16 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.*;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collections; import java.util.Collections;
import java.util.Comparator; import java.util.Comparator;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* 合成注解{@link GenericSynthesizedAggregateAnnotation}的测试用例 * 合成注解{@link GenericSynthesizedAggregateAnnotation}的测试用例
* *
@ -31,44 +28,44 @@ public class GenericSynthesizedAggregateAnnotationTest {
final GenericSynthesizedAggregateAnnotation syntheticMetaAnnotation = new GenericSynthesizedAggregateAnnotation(childAnnotation); final GenericSynthesizedAggregateAnnotation syntheticMetaAnnotation = new GenericSynthesizedAggregateAnnotation(childAnnotation);
// Annotation & AnnotatedElement // Annotation & AnnotatedElement
Assert.assertEquals(GenericSynthesizedAggregateAnnotation.class, syntheticMetaAnnotation.annotationType()); assertEquals(GenericSynthesizedAggregateAnnotation.class, syntheticMetaAnnotation.annotationType());
Assert.assertTrue(syntheticMetaAnnotation.isAnnotationPresent(GrandParentAnnotation.class)); assertTrue(syntheticMetaAnnotation.isAnnotationPresent(GrandParentAnnotation.class));
Assert.assertTrue(syntheticMetaAnnotation.isAnnotationPresent(ParentAnnotation.class)); assertTrue(syntheticMetaAnnotation.isAnnotationPresent(ParentAnnotation.class));
Assert.assertTrue(syntheticMetaAnnotation.isAnnotationPresent(ChildAnnotation.class)); assertTrue(syntheticMetaAnnotation.isAnnotationPresent(ChildAnnotation.class));
Assert.assertEquals(grandParentAnnotation, syntheticMetaAnnotation.getAnnotation(GrandParentAnnotation.class)); assertEquals(grandParentAnnotation, syntheticMetaAnnotation.getAnnotation(GrandParentAnnotation.class));
Assert.assertEquals(parentAnnotation, syntheticMetaAnnotation.getAnnotation(ParentAnnotation.class)); assertEquals(parentAnnotation, syntheticMetaAnnotation.getAnnotation(ParentAnnotation.class));
Assert.assertEquals(childAnnotation, syntheticMetaAnnotation.getAnnotation(ChildAnnotation.class)); assertEquals(childAnnotation, syntheticMetaAnnotation.getAnnotation(ChildAnnotation.class));
Annotation[] synthesizedAnnotations = syntheticMetaAnnotation.getAnnotations(); Annotation[] synthesizedAnnotations = syntheticMetaAnnotation.getAnnotations();
Arrays.sort(synthesizedAnnotations, Comparator.comparing(Annotation::toString)); Arrays.sort(synthesizedAnnotations, Comparator.comparing(Annotation::toString));
Assert.assertEquals( assertEquals(
Arrays.asList(childAnnotation, grandParentAnnotation, parentAnnotation), Arrays.asList(childAnnotation, grandParentAnnotation, parentAnnotation),
Arrays.asList(synthesizedAnnotations) Arrays.asList(synthesizedAnnotations)
); );
// 扩展方法 // 扩展方法
Assert.assertNotNull(syntheticMetaAnnotation.getSynthesizedAnnotation(GrandParentAnnotation.class)); assertNotNull(syntheticMetaAnnotation.getSynthesizedAnnotation(GrandParentAnnotation.class));
Assert.assertNotNull(syntheticMetaAnnotation.getSynthesizedAnnotation(ParentAnnotation.class)); assertNotNull(syntheticMetaAnnotation.getSynthesizedAnnotation(ParentAnnotation.class));
Assert.assertNotNull(syntheticMetaAnnotation.getSynthesizedAnnotation(ChildAnnotation.class)); assertNotNull(syntheticMetaAnnotation.getSynthesizedAnnotation(ChildAnnotation.class));
Assert.assertEquals(3, syntheticMetaAnnotation.getAllSynthesizedAnnotation().size()); assertEquals(3, syntheticMetaAnnotation.getAllSynthesizedAnnotation().size());
// 属性 // 属性
Assert.assertEquals(SynthesizedAnnotationSelector.NEAREST_AND_OLDEST_PRIORITY, syntheticMetaAnnotation.getAnnotationSelector()); assertEquals(SynthesizedAnnotationSelector.NEAREST_AND_OLDEST_PRIORITY, syntheticMetaAnnotation.getAnnotationSelector());
Assert.assertEquals(CacheableSynthesizedAnnotationAttributeProcessor.class, syntheticMetaAnnotation.getAnnotationAttributeProcessor().getClass()); assertEquals(CacheableSynthesizedAnnotationAttributeProcessor.class, syntheticMetaAnnotation.getAnnotationAttributeProcessor().getClass());
Assert.assertEquals(3, syntheticMetaAnnotation.getAnnotationPostProcessors().size()); assertEquals(3, syntheticMetaAnnotation.getAnnotationPostProcessors().size());
} }
@Test @Test
public void synthesisAnnotationAttributeTest() { public void synthesisAnnotationAttributeTest() {
final ChildAnnotation rootAnnotation = AnnotatedClass.class.getAnnotation(ChildAnnotation.class); final ChildAnnotation rootAnnotation = AnnotatedClass.class.getAnnotation(ChildAnnotation.class);
GenericSynthesizedAggregateAnnotation syntheticMetaAnnotation = new GenericSynthesizedAggregateAnnotation(rootAnnotation); GenericSynthesizedAggregateAnnotation syntheticMetaAnnotation = new GenericSynthesizedAggregateAnnotation(rootAnnotation);
Assert.assertEquals(syntheticMetaAnnotation.getSource(), Collections.singletonList(rootAnnotation)); assertEquals(syntheticMetaAnnotation.getSource(), Collections.singletonList(rootAnnotation));
Assert.assertEquals(syntheticMetaAnnotation.annotationType(), GenericSynthesizedAggregateAnnotation.class); assertEquals(syntheticMetaAnnotation.annotationType(), GenericSynthesizedAggregateAnnotation.class);
Assert.assertEquals(3, syntheticMetaAnnotation.getAnnotations().length); assertEquals(3, syntheticMetaAnnotation.getAnnotations().length);
Assert.assertEquals("Child!", syntheticMetaAnnotation.getAttributeValue("childValue", String.class)); assertEquals("Child!", syntheticMetaAnnotation.getAttributeValue("childValue", String.class));
Assert.assertEquals("Child!", syntheticMetaAnnotation.getAttributeValue("childValueAlias", String.class)); assertEquals("Child!", syntheticMetaAnnotation.getAttributeValue("childValueAlias", String.class));
Assert.assertEquals("Child's Parent!", syntheticMetaAnnotation.getAttributeValue("parentValue", String.class)); assertEquals("Child's Parent!", syntheticMetaAnnotation.getAttributeValue("parentValue", String.class));
Assert.assertEquals("Child's GrandParent!", syntheticMetaAnnotation.getAttributeValue("grandParentValue", String.class)); assertEquals("Child's GrandParent!", syntheticMetaAnnotation.getAttributeValue("grandParentValue", String.class));
} }
@Test @Test
@ -78,39 +75,39 @@ public class GenericSynthesizedAggregateAnnotationTest {
final ChildAnnotation childAnnotation = syntheticMetaAnnotation.synthesize(ChildAnnotation.class); final ChildAnnotation childAnnotation = syntheticMetaAnnotation.synthesize(ChildAnnotation.class);
SynthesizedAnnotation childSyntheticAnnotation = syntheticMetaAnnotation.getSynthesizedAnnotation(ChildAnnotation.class); SynthesizedAnnotation childSyntheticAnnotation = syntheticMetaAnnotation.getSynthesizedAnnotation(ChildAnnotation.class);
Assert.assertNotNull(childSyntheticAnnotation); assertNotNull(childSyntheticAnnotation);
Assert.assertTrue(childSyntheticAnnotation.hasAttribute("childValue", String.class)); assertTrue(childSyntheticAnnotation.hasAttribute("childValue", String.class));
Assert.assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), childSyntheticAnnotation.getRoot()); assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), childSyntheticAnnotation.getRoot());
Assert.assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), childSyntheticAnnotation.getAnnotation()); assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), childSyntheticAnnotation.getAnnotation());
Assert.assertTrue(syntheticMetaAnnotation.isAnnotationPresent(ChildAnnotation.class)); assertTrue(syntheticMetaAnnotation.isAnnotationPresent(ChildAnnotation.class));
Assert.assertNotNull(childAnnotation); assertNotNull(childAnnotation);
Assert.assertEquals("Child!", childAnnotation.childValue()); assertEquals("Child!", childAnnotation.childValue());
Assert.assertEquals("Child!", childAnnotation.childValueAlias()); assertEquals("Child!", childAnnotation.childValueAlias());
Assert.assertEquals(childAnnotation.grandParentType(), Integer.class); assertEquals(childAnnotation.grandParentType(), Integer.class);
Assert.assertThrows(IllegalArgumentException.class, () -> new GenericSynthesizedAggregateAnnotation(childAnnotation)); assertThrows(IllegalArgumentException.class, () -> new GenericSynthesizedAggregateAnnotation(childAnnotation));
final ParentAnnotation parentAnnotation = syntheticMetaAnnotation.synthesize(ParentAnnotation.class); final ParentAnnotation parentAnnotation = syntheticMetaAnnotation.synthesize(ParentAnnotation.class);
SynthesizedAnnotation parentSyntheticAnnotation = syntheticMetaAnnotation.getSynthesizedAnnotation(ParentAnnotation.class); SynthesizedAnnotation parentSyntheticAnnotation = syntheticMetaAnnotation.getSynthesizedAnnotation(ParentAnnotation.class);
Assert.assertNotNull(parentSyntheticAnnotation); assertNotNull(parentSyntheticAnnotation);
Assert.assertTrue(parentSyntheticAnnotation.hasAttribute("parentValue", String.class)); assertTrue(parentSyntheticAnnotation.hasAttribute("parentValue", String.class));
Assert.assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), parentSyntheticAnnotation.getRoot()); assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), parentSyntheticAnnotation.getRoot());
Assert.assertEquals(ChildAnnotation.class.getAnnotation(ParentAnnotation.class), parentSyntheticAnnotation.getAnnotation()); assertEquals(ChildAnnotation.class.getAnnotation(ParentAnnotation.class), parentSyntheticAnnotation.getAnnotation());
Assert.assertNotNull(parentAnnotation); assertNotNull(parentAnnotation);
Assert.assertEquals("Child's Parent!", parentAnnotation.parentValue()); assertEquals("Child's Parent!", parentAnnotation.parentValue());
Assert.assertEquals("java.lang.Void", parentAnnotation.grandParentType()); assertEquals("java.lang.Void", parentAnnotation.grandParentType());
Assert.assertThrows(IllegalArgumentException.class, () -> new GenericSynthesizedAggregateAnnotation(parentAnnotation)); assertThrows(IllegalArgumentException.class, () -> new GenericSynthesizedAggregateAnnotation(parentAnnotation));
final GrandParentAnnotation grandParentAnnotation = syntheticMetaAnnotation.synthesize(GrandParentAnnotation.class); final GrandParentAnnotation grandParentAnnotation = syntheticMetaAnnotation.synthesize(GrandParentAnnotation.class);
SynthesizedAnnotation grandParentSyntheticAnnotation = syntheticMetaAnnotation.getSynthesizedAnnotation(GrandParentAnnotation.class); SynthesizedAnnotation grandParentSyntheticAnnotation = syntheticMetaAnnotation.getSynthesizedAnnotation(GrandParentAnnotation.class);
Assert.assertNotNull(grandParentSyntheticAnnotation); assertNotNull(grandParentSyntheticAnnotation);
Assert.assertTrue(grandParentSyntheticAnnotation.hasAttribute("grandParentType", Class.class)); assertTrue(grandParentSyntheticAnnotation.hasAttribute("grandParentType", Class.class));
Assert.assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), grandParentSyntheticAnnotation.getRoot()); assertEquals(AnnotatedClass.class.getAnnotation(ChildAnnotation.class), grandParentSyntheticAnnotation.getRoot());
Assert.assertEquals(ChildAnnotation.class.getAnnotation(GrandParentAnnotation.class), grandParentSyntheticAnnotation.getAnnotation()); assertEquals(ChildAnnotation.class.getAnnotation(GrandParentAnnotation.class), grandParentSyntheticAnnotation.getAnnotation());
Assert.assertTrue(syntheticMetaAnnotation.isAnnotationPresent(GrandParentAnnotation.class)); assertTrue(syntheticMetaAnnotation.isAnnotationPresent(GrandParentAnnotation.class));
Assert.assertNotNull(grandParentAnnotation); assertNotNull(grandParentAnnotation);
Assert.assertEquals("Child's GrandParent!", grandParentAnnotation.grandParentValue()); assertEquals("Child's GrandParent!", grandParentAnnotation.grandParentValue());
Assert.assertEquals(grandParentAnnotation.grandParentType(), Integer.class); assertEquals(grandParentAnnotation.grandParentType(), Integer.class);
Assert.assertThrows(IllegalArgumentException.class, () -> new GenericSynthesizedAggregateAnnotation(grandParentAnnotation)); assertThrows(IllegalArgumentException.class, () -> new GenericSynthesizedAggregateAnnotation(grandParentAnnotation));
} }
@Test @Test
@ -118,8 +115,8 @@ public class GenericSynthesizedAggregateAnnotationTest {
final Method method = ReflectUtil.getMethod(AnnotationForLinkTest.class, "value"); final Method method = ReflectUtil.getMethod(AnnotationForLinkTest.class, "value");
final SynthesizedAggregateAnnotation synthesizedAnnotationAggregator = new GenericSynthesizedAggregateAnnotation(method.getAnnotation(AliasFor.class)); final SynthesizedAggregateAnnotation synthesizedAnnotationAggregator = new GenericSynthesizedAggregateAnnotation(method.getAnnotation(AliasFor.class));
final Link link = synthesizedAnnotationAggregator.synthesize(Link.class); final Link link = synthesizedAnnotationAggregator.synthesize(Link.class);
Assert.assertEquals(AnnotationForLinkTest.class, link.annotation()); assertEquals(AnnotationForLinkTest.class, link.annotation());
Assert.assertEquals("name", link.attribute()); assertEquals("name", link.attribute());
} }
@Test @Test
@ -127,20 +124,20 @@ public class GenericSynthesizedAggregateAnnotationTest {
AnnotationForMirrorTest annotation = ClassForMirrorTest.class.getAnnotation(AnnotationForMirrorTest.class); AnnotationForMirrorTest annotation = ClassForMirrorTest.class.getAnnotation(AnnotationForMirrorTest.class);
SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation); SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
AnnotationForMirrorTest syntheticAnnotation = synthetic.synthesize(AnnotationForMirrorTest.class); AnnotationForMirrorTest syntheticAnnotation = synthetic.synthesize(AnnotationForMirrorTest.class);
Assert.assertEquals("Foo", syntheticAnnotation.name()); assertEquals("Foo", syntheticAnnotation.name());
Assert.assertEquals("Foo", syntheticAnnotation.value()); assertEquals("Foo", syntheticAnnotation.value());
annotation = ClassForMirrorTest2.class.getAnnotation(AnnotationForMirrorTest.class); annotation = ClassForMirrorTest2.class.getAnnotation(AnnotationForMirrorTest.class);
synthetic = new GenericSynthesizedAggregateAnnotation(annotation); synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
syntheticAnnotation = synthetic.synthesize(AnnotationForMirrorTest.class); syntheticAnnotation = synthetic.synthesize(AnnotationForMirrorTest.class);
Assert.assertEquals("Foo", syntheticAnnotation.name()); assertEquals("Foo", syntheticAnnotation.name());
Assert.assertEquals("Foo", syntheticAnnotation.value()); assertEquals("Foo", syntheticAnnotation.value());
annotation = ClassForMirrorTest3.class.getAnnotation(AnnotationForMirrorTest.class); annotation = ClassForMirrorTest3.class.getAnnotation(AnnotationForMirrorTest.class);
synthetic = new GenericSynthesizedAggregateAnnotation(annotation); synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
syntheticAnnotation = synthetic.synthesize(AnnotationForMirrorTest.class); syntheticAnnotation = synthetic.synthesize(AnnotationForMirrorTest.class);
AnnotationForMirrorTest finalSyntheticAnnotation = syntheticAnnotation; AnnotationForMirrorTest finalSyntheticAnnotation = syntheticAnnotation;
Assert.assertThrows(IllegalArgumentException.class, finalSyntheticAnnotation::name); assertThrows(IllegalArgumentException.class, finalSyntheticAnnotation::name);
} }
@Test @Test
@ -148,16 +145,16 @@ public class GenericSynthesizedAggregateAnnotationTest {
AnnotationForAliasForTest annotation = ClassForAliasForTest.class.getAnnotation(AnnotationForAliasForTest.class); AnnotationForAliasForTest annotation = ClassForAliasForTest.class.getAnnotation(AnnotationForAliasForTest.class);
SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation); SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
MetaAnnotationForAliasForTest metaAnnotation = synthetic.synthesize(MetaAnnotationForAliasForTest.class); MetaAnnotationForAliasForTest metaAnnotation = synthetic.synthesize(MetaAnnotationForAliasForTest.class);
Assert.assertEquals("Meta", metaAnnotation.name()); assertEquals("Meta", metaAnnotation.name());
AnnotationForAliasForTest childAnnotation = synthetic.synthesize(AnnotationForAliasForTest.class); AnnotationForAliasForTest childAnnotation = synthetic.synthesize(AnnotationForAliasForTest.class);
Assert.assertEquals("", childAnnotation.value()); assertEquals("", childAnnotation.value());
annotation = ClassForAliasForTest2.class.getAnnotation(AnnotationForAliasForTest.class); annotation = ClassForAliasForTest2.class.getAnnotation(AnnotationForAliasForTest.class);
synthetic = new GenericSynthesizedAggregateAnnotation(annotation); synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
metaAnnotation = synthetic.synthesize(MetaAnnotationForAliasForTest.class); metaAnnotation = synthetic.synthesize(MetaAnnotationForAliasForTest.class);
Assert.assertEquals("Foo", metaAnnotation.name()); assertEquals("Foo", metaAnnotation.name());
childAnnotation = synthetic.synthesize(AnnotationForAliasForTest.class); childAnnotation = synthetic.synthesize(AnnotationForAliasForTest.class);
Assert.assertEquals("Foo", childAnnotation.value()); assertEquals("Foo", childAnnotation.value());
} }
@Test @Test
@ -165,16 +162,16 @@ public class GenericSynthesizedAggregateAnnotationTest {
AnnotationForceForAliasForTest annotation = ClassForForceAliasForTest.class.getAnnotation(AnnotationForceForAliasForTest.class); AnnotationForceForAliasForTest annotation = ClassForForceAliasForTest.class.getAnnotation(AnnotationForceForAliasForTest.class);
SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation); SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
MetaAnnotationForForceAliasForTest metaAnnotation = synthetic.synthesize(MetaAnnotationForForceAliasForTest.class); MetaAnnotationForForceAliasForTest metaAnnotation = synthetic.synthesize(MetaAnnotationForForceAliasForTest.class);
Assert.assertEquals("", metaAnnotation.name()); assertEquals("", metaAnnotation.name());
AnnotationForceForAliasForTest childAnnotation = synthetic.synthesize(AnnotationForceForAliasForTest.class); AnnotationForceForAliasForTest childAnnotation = synthetic.synthesize(AnnotationForceForAliasForTest.class);
Assert.assertEquals("", childAnnotation.value()); assertEquals("", childAnnotation.value());
annotation = ClassForForceAliasForTest2.class.getAnnotation(AnnotationForceForAliasForTest.class); annotation = ClassForForceAliasForTest2.class.getAnnotation(AnnotationForceForAliasForTest.class);
synthetic = new GenericSynthesizedAggregateAnnotation(annotation); synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
metaAnnotation = synthetic.synthesize(MetaAnnotationForForceAliasForTest.class); metaAnnotation = synthetic.synthesize(MetaAnnotationForForceAliasForTest.class);
Assert.assertEquals("Foo", metaAnnotation.name()); assertEquals("Foo", metaAnnotation.name());
childAnnotation = synthetic.synthesize(AnnotationForceForAliasForTest.class); childAnnotation = synthetic.synthesize(AnnotationForceForAliasForTest.class);
Assert.assertEquals("Foo", childAnnotation.value()); assertEquals("Foo", childAnnotation.value());
} }
@Test @Test
@ -182,10 +179,10 @@ public class GenericSynthesizedAggregateAnnotationTest {
AnnotationForMirrorThenAliasForTest annotation = ClassForAliasForAndMirrorTest.class.getAnnotation(AnnotationForMirrorThenAliasForTest.class); AnnotationForMirrorThenAliasForTest annotation = ClassForAliasForAndMirrorTest.class.getAnnotation(AnnotationForMirrorThenAliasForTest.class);
SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation); SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
MetaAnnotationForMirrorThenAliasForTest metaAnnotation = synthetic.synthesize(MetaAnnotationForMirrorThenAliasForTest.class); MetaAnnotationForMirrorThenAliasForTest metaAnnotation = synthetic.synthesize(MetaAnnotationForMirrorThenAliasForTest.class);
Assert.assertEquals("test", metaAnnotation.name()); assertEquals("test", metaAnnotation.name());
Assert.assertEquals("test", metaAnnotation.value()); assertEquals("test", metaAnnotation.value());
AnnotationForMirrorThenAliasForTest childAnnotation = synthetic.synthesize(AnnotationForMirrorThenAliasForTest.class); AnnotationForMirrorThenAliasForTest childAnnotation = synthetic.synthesize(AnnotationForMirrorThenAliasForTest.class);
Assert.assertEquals("test", childAnnotation.childValue()); assertEquals("test", childAnnotation.childValue());
} }
@Test @Test
@ -194,12 +191,12 @@ public class GenericSynthesizedAggregateAnnotationTest {
final SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation); final SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
final MetaAnnotationForMultiAliasForTest1 metaAnnotation1 = synthetic.synthesize(MetaAnnotationForMultiAliasForTest1.class); final MetaAnnotationForMultiAliasForTest1 metaAnnotation1 = synthetic.synthesize(MetaAnnotationForMultiAliasForTest1.class);
Assert.assertEquals("test", metaAnnotation1.name()); assertEquals("test", metaAnnotation1.name());
Assert.assertEquals("test", metaAnnotation1.value1()); assertEquals("test", metaAnnotation1.value1());
final MetaAnnotationForMultiAliasForTest2 metaAnnotation2 = synthetic.synthesize(MetaAnnotationForMultiAliasForTest2.class); final MetaAnnotationForMultiAliasForTest2 metaAnnotation2 = synthetic.synthesize(MetaAnnotationForMultiAliasForTest2.class);
Assert.assertEquals("test", metaAnnotation2.value2()); assertEquals("test", metaAnnotation2.value2());
final AnnotationForMultiAliasForTest childAnnotation = synthetic.synthesize(AnnotationForMultiAliasForTest.class); final AnnotationForMultiAliasForTest childAnnotation = synthetic.synthesize(AnnotationForMultiAliasForTest.class);
Assert.assertEquals("test", childAnnotation.value3()); assertEquals("test", childAnnotation.value3());
} }
@Test @Test
@ -208,10 +205,10 @@ public class GenericSynthesizedAggregateAnnotationTest {
final SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation); final SynthesizedAggregateAnnotation synthetic = new GenericSynthesizedAggregateAnnotation(annotation);
final MetaAnnotationForImplicitAliasTest metaAnnotation = synthetic.synthesize(MetaAnnotationForImplicitAliasTest.class); final MetaAnnotationForImplicitAliasTest metaAnnotation = synthetic.synthesize(MetaAnnotationForImplicitAliasTest.class);
Assert.assertEquals("Meta", metaAnnotation.name()); assertEquals("Meta", metaAnnotation.name());
Assert.assertEquals("Foo", metaAnnotation.value()); assertEquals("Foo", metaAnnotation.value());
final AnnotationForImplicitAliasTest childAnnotation = synthetic.synthesize(AnnotationForImplicitAliasTest.class); final AnnotationForImplicitAliasTest childAnnotation = synthetic.synthesize(AnnotationForImplicitAliasTest.class);
Assert.assertEquals("Foo", childAnnotation.value()); assertEquals("Foo", childAnnotation.value());
} }
// 注解结构如下 // 注解结构如下

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation;
import cn.hutool.core.util.ObjectUtil; import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -26,17 +26,17 @@ public class MirrorLinkAnnotationPostProcessorTest {
processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator); processor.process(synthesizedAnnotation, synthesizedAnnotationAggregator);
AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value"); AnnotationAttribute valueAttribute = synthesizedAnnotation.getAttributes().get("value");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value"), valueAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "value"), valueAttribute.getAttribute());
Assert.assertTrue(valueAttribute.isWrapped()); assertTrue(valueAttribute.isWrapped());
Assert.assertEquals(MirroredAnnotationAttribute.class, valueAttribute.getClass()); assertEquals(MirroredAnnotationAttribute.class, valueAttribute.getClass());
AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name"); AnnotationAttribute nameAttribute = synthesizedAnnotation.getAttributes().get("name");
Assert.assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name"), nameAttribute.getAttribute()); assertEquals(ReflectUtil.getMethod(AnnotationForTest.class, "name"), nameAttribute.getAttribute());
Assert.assertTrue(nameAttribute.isWrapped()); assertTrue(nameAttribute.isWrapped());
Assert.assertEquals(MirroredAnnotationAttribute.class, nameAttribute.getClass()); assertEquals(MirroredAnnotationAttribute.class, nameAttribute.getClass());
Assert.assertEquals(((WrappedAnnotationAttribute)nameAttribute).getLinked(), ((WrappedAnnotationAttribute)valueAttribute).getOriginal()); assertEquals(((WrappedAnnotationAttribute)nameAttribute).getLinked(), ((WrappedAnnotationAttribute)valueAttribute).getOriginal());
Assert.assertEquals(((WrappedAnnotationAttribute)nameAttribute).getOriginal(), ((WrappedAnnotationAttribute)valueAttribute).getLinked()); assertEquals(((WrappedAnnotationAttribute)nameAttribute).getOriginal(), ((WrappedAnnotationAttribute)valueAttribute).getLinked());
} }
@AnnotationForTest @AnnotationForTest

View File

@ -1,8 +1,8 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -20,12 +20,12 @@ public class MirroredAnnotationAttributeTest {
final MirroredAnnotationAttribute nameAnnotationAttribute = new MirroredAnnotationAttribute(nameAttribute, valueAttribute); final MirroredAnnotationAttribute nameAnnotationAttribute = new MirroredAnnotationAttribute(nameAttribute, valueAttribute);
// 注解属性 // 注解属性
Assert.assertEquals(annotation, nameAnnotationAttribute.getAnnotation()); assertEquals(annotation, nameAnnotationAttribute.getAnnotation());
Assert.assertEquals(annotation.annotationType(), nameAnnotationAttribute.getAnnotationType()); assertEquals(annotation.annotationType(), nameAnnotationAttribute.getAnnotationType());
// 方法属性 // 方法属性
Assert.assertEquals(nameMethod.getName(), nameAnnotationAttribute.getAttributeName()); assertEquals(nameMethod.getName(), nameAnnotationAttribute.getAttributeName());
Assert.assertEquals(nameMethod.getReturnType(), nameAnnotationAttribute.getAttributeType()); assertEquals(nameMethod.getReturnType(), nameAnnotationAttribute.getAttributeType());
} }
@Test @Test
@ -39,9 +39,9 @@ public class MirroredAnnotationAttributeTest {
final MirroredAnnotationAttribute nameAnnotationAttribute = new MirroredAnnotationAttribute(nameAttribute, valueAttribute); final MirroredAnnotationAttribute nameAnnotationAttribute = new MirroredAnnotationAttribute(nameAttribute, valueAttribute);
// 值处理 // 值处理
Assert.assertEquals("", nameAnnotationAttribute.getValue()); assertEquals("", nameAnnotationAttribute.getValue());
Assert.assertTrue(nameAnnotationAttribute.isValueEquivalentToDefaultValue()); assertTrue(nameAnnotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertTrue(nameAnnotationAttribute.isWrapped()); assertTrue(nameAnnotationAttribute.isWrapped());
} }
@Test @Test
@ -55,9 +55,9 @@ public class MirroredAnnotationAttributeTest {
final MirroredAnnotationAttribute nameAnnotationAttribute = new MirroredAnnotationAttribute(nameAttribute, valueAttribute); final MirroredAnnotationAttribute nameAnnotationAttribute = new MirroredAnnotationAttribute(nameAttribute, valueAttribute);
// 值处理 // 值处理
Assert.assertEquals("name", nameAnnotationAttribute.getValue()); assertEquals("name", nameAnnotationAttribute.getValue());
Assert.assertFalse(nameAnnotationAttribute.isValueEquivalentToDefaultValue()); assertFalse(nameAnnotationAttribute.isValueEquivalentToDefaultValue());
Assert.assertTrue(nameAnnotationAttribute.isWrapped()); assertTrue(nameAnnotationAttribute.isWrapped());
} }
@Retention(RetentionPolicy.RUNTIME) @Retention(RetentionPolicy.RUNTIME)

View File

@ -1,7 +1,7 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.Map; import java.util.Map;
@ -15,15 +15,15 @@ public class SynthesizedAnnotationSelectorTest {
TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0);
TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation1, selector.choose(annotation1, annotation2)); assertEquals(annotation1, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(0, 1); annotation1 = new TestSynthesizedAnnotation(0, 1);
annotation2 = new TestSynthesizedAnnotation(0, 0); annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation1, selector.choose(annotation1, annotation2)); assertEquals(annotation1, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(1, 0); annotation1 = new TestSynthesizedAnnotation(1, 0);
annotation2 = new TestSynthesizedAnnotation(0, 0); annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation2, selector.choose(annotation1, annotation2)); assertEquals(annotation2, selector.choose(annotation1, annotation2));
} }
@Test @Test
@ -32,15 +32,15 @@ public class SynthesizedAnnotationSelectorTest {
TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0);
TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation2, selector.choose(annotation1, annotation2)); assertEquals(annotation2, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(0, 1); annotation1 = new TestSynthesizedAnnotation(0, 1);
annotation2 = new TestSynthesizedAnnotation(0, 0); annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation2, selector.choose(annotation1, annotation2)); assertEquals(annotation2, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(0, 0); annotation1 = new TestSynthesizedAnnotation(0, 0);
annotation2 = new TestSynthesizedAnnotation(1, 0); annotation2 = new TestSynthesizedAnnotation(1, 0);
Assert.assertEquals(annotation1, selector.choose(annotation1, annotation2)); assertEquals(annotation1, selector.choose(annotation1, annotation2));
} }
@Test @Test
@ -49,15 +49,15 @@ public class SynthesizedAnnotationSelectorTest {
TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0);
TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation1, selector.choose(annotation1, annotation2)); assertEquals(annotation1, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(0, 1); annotation1 = new TestSynthesizedAnnotation(0, 1);
annotation2 = new TestSynthesizedAnnotation(0, 0); annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation1, selector.choose(annotation1, annotation2)); assertEquals(annotation1, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(0, 0); annotation1 = new TestSynthesizedAnnotation(0, 0);
annotation2 = new TestSynthesizedAnnotation(1, 0); annotation2 = new TestSynthesizedAnnotation(1, 0);
Assert.assertEquals(annotation2, selector.choose(annotation1, annotation2)); assertEquals(annotation2, selector.choose(annotation1, annotation2));
} }
@Test @Test
@ -66,15 +66,15 @@ public class SynthesizedAnnotationSelectorTest {
TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation1 = new TestSynthesizedAnnotation(0, 0);
TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0); TestSynthesizedAnnotation annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation2, selector.choose(annotation1, annotation2)); assertEquals(annotation2, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(0, 1); annotation1 = new TestSynthesizedAnnotation(0, 1);
annotation2 = new TestSynthesizedAnnotation(0, 0); annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation2, selector.choose(annotation1, annotation2)); assertEquals(annotation2, selector.choose(annotation1, annotation2));
annotation1 = new TestSynthesizedAnnotation(1, 0); annotation1 = new TestSynthesizedAnnotation(1, 0);
annotation2 = new TestSynthesizedAnnotation(0, 0); annotation2 = new TestSynthesizedAnnotation(0, 0);
Assert.assertEquals(annotation1, selector.choose(annotation1, annotation2)); assertEquals(annotation1, selector.choose(annotation1, annotation2));
} }
static class TestSynthesizedAnnotation implements SynthesizedAnnotation { static class TestSynthesizedAnnotation implements SynthesizedAnnotation {

View File

@ -1,7 +1,7 @@
package cn.hutool.core.annotation; package cn.hutool.core.annotation;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.annotation.ElementType; import java.lang.annotation.ElementType;
@ -20,9 +20,9 @@ public class TestIssueI8CLBJ {
@Test @Test
public void test() throws NoSuchFieldException { public void test() throws NoSuchFieldException {
Field field = Foo.class.getDeclaredField("name"); Field field = Foo.class.getDeclaredField("name");
Assert.assertNotNull(field); assertNotNull(field);
Annotation[] annotations = field.getDeclaredAnnotations(); Annotation[] annotations = field.getDeclaredAnnotations();
Assert.assertTrue(annotations.length > 0); assertTrue(annotations.length > 0);
TestAnnotation annotation = AnnotationUtil.getSynthesizedAnnotation(TestAnnotation.class, annotations); TestAnnotation annotation = AnnotationUtil.getSynthesizedAnnotation(TestAnnotation.class, annotations);
List<Thread> threadList = new ArrayList<>(); List<Thread> threadList = new ArrayList<>();

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation.scanner;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -17,21 +17,21 @@ public class ElementAnnotationScannerTest {
@Test @Test
public void supportTest() { public void supportTest() {
final ElementAnnotationScanner scanner = new ElementAnnotationScanner(); final ElementAnnotationScanner scanner = new ElementAnnotationScanner();
Assert.assertTrue(scanner.support(ReflectUtil.getField(FieldAnnotationScannerTest.Example.class, "id"))); assertTrue(scanner.support(ReflectUtil.getField(FieldAnnotationScannerTest.Example.class, "id")));
Assert.assertTrue(scanner.support(ReflectUtil.getMethod(FieldAnnotationScannerTest.Example.class, "getId"))); assertTrue(scanner.support(ReflectUtil.getMethod(FieldAnnotationScannerTest.Example.class, "getId")));
Assert.assertFalse(scanner.support(null)); assertFalse(scanner.support(null));
Assert.assertTrue(scanner.support(FieldAnnotationScannerTest.Example.class)); assertTrue(scanner.support(FieldAnnotationScannerTest.Example.class));
} }
@Test @Test
public void getAnnotationsTest() { public void getAnnotationsTest() {
final ElementAnnotationScanner scanner = new ElementAnnotationScanner(); final ElementAnnotationScanner scanner = new ElementAnnotationScanner();
final Field field = ReflectUtil.getField(FieldAnnotationScannerTest.Example.class, "id"); final Field field = ReflectUtil.getField(FieldAnnotationScannerTest.Example.class, "id");
Assert.assertNotNull(field); assertNotNull(field);
Assert.assertTrue(scanner.support(field)); assertTrue(scanner.support(field));
List<Annotation> annotations = scanner.getAnnotations(field); List<Annotation> annotations = scanner.getAnnotations(field);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
Assert.assertEquals(AnnotationForScannerTest.class, CollUtil.getFirst(annotations).annotationType()); assertEquals(AnnotationForScannerTest.class, CollUtil.getFirst(annotations).annotationType());
} }
@Test @Test
@ -43,9 +43,9 @@ public class ElementAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
field, null field, null
); );
Assert.assertEquals(1, map.size()); assertEquals(1, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals(AnnotationForScannerTest.class, map.get(0).get(0).annotationType()); assertEquals(AnnotationForScannerTest.class, map.get(0).get(0).annotationType());
} }
public static class Example { public static class Example {

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation.scanner;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Field; import java.lang.reflect.Field;
@ -17,21 +17,21 @@ public class FieldAnnotationScannerTest {
@Test @Test
public void supportTest() { public void supportTest() {
AnnotationScanner scanner = new FieldAnnotationScanner(); AnnotationScanner scanner = new FieldAnnotationScanner();
Assert.assertTrue(scanner.support(ReflectUtil.getField(Example.class, "id"))); assertTrue(scanner.support(ReflectUtil.getField(Example.class, "id")));
Assert.assertFalse(scanner.support(ReflectUtil.getMethod(Example.class, "getId"))); assertFalse(scanner.support(ReflectUtil.getMethod(Example.class, "getId")));
Assert.assertFalse(scanner.support(null)); assertFalse(scanner.support(null));
Assert.assertFalse(scanner.support(Example.class)); assertFalse(scanner.support(Example.class));
} }
@Test @Test
public void getAnnotationsTest() { public void getAnnotationsTest() {
AnnotationScanner scanner = new FieldAnnotationScanner(); AnnotationScanner scanner = new FieldAnnotationScanner();
Field field = ReflectUtil.getField(Example.class, "id"); Field field = ReflectUtil.getField(Example.class, "id");
Assert.assertNotNull(field); assertNotNull(field);
Assert.assertTrue(scanner.support(field)); assertTrue(scanner.support(field));
List<Annotation> annotations = scanner.getAnnotations(field); List<Annotation> annotations = scanner.getAnnotations(field);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
Assert.assertEquals(AnnotationForScannerTest.class, CollUtil.getFirst(annotations).annotationType()); assertEquals(AnnotationForScannerTest.class, CollUtil.getFirst(annotations).annotationType());
} }
@Test @Test
@ -43,9 +43,9 @@ public class FieldAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
field, null field, null
); );
Assert.assertEquals(1, map.size()); assertEquals(1, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals(AnnotationForScannerTest.class, map.get(0).get(0).annotationType()); assertEquals(AnnotationForScannerTest.class, map.get(0).get(0).annotationType());
} }
public static class Example { public static class Example {

View File

@ -1,7 +1,7 @@
package cn.hutool.core.annotation.scanner; package cn.hutool.core.annotation.scanner;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.util.List; import java.util.List;
@ -12,56 +12,56 @@ public class GenericAnnotationScannerTest {
public void scanDirectlyTest() { public void scanDirectlyTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, false, false); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, false, false);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
} }
@Test @Test
public void scanDirectlyAndMetaAnnotationTest() { public void scanDirectlyAndMetaAnnotationTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, false, false); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, false, false);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
} }
@Test @Test
public void scanSuperclassTest() { public void scanSuperclassTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, true, false); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, true, false);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
} }
@Test @Test
public void scanSuperclassAndMetaAnnotationTest() { public void scanSuperclassAndMetaAnnotationTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, true, false); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, true, false);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(4, annotations.size()); assertEquals(4, annotations.size());
} }
@Test @Test
public void scanInterfaceTest() { public void scanInterfaceTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, false, true); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, false, true);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
} }
@Test @Test
public void scanInterfaceAndMetaAnnotationTest() { public void scanInterfaceAndMetaAnnotationTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, false, true); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, false, true);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(4, annotations.size()); assertEquals(4, annotations.size());
} }
@Test @Test
public void scanTypeHierarchyTest() { public void scanTypeHierarchyTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, true, true); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(false, true, true);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(3, annotations.size()); assertEquals(3, annotations.size());
} }
@Test @Test
public void scanTypeHierarchyAndMetaAnnotationTest() { public void scanTypeHierarchyAndMetaAnnotationTest() {
final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, true, true); final GenericAnnotationScanner scanner = new GenericAnnotationScanner(true, true, true);
final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class); final List<Annotation> annotations = scanner.getAnnotations(ClassForTest.class);
Assert.assertEquals(6, annotations.size()); assertEquals(6, annotations.size());
} }
@Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD}) @Target({ElementType.ANNOTATION_TYPE, ElementType.TYPE, ElementType.METHOD})

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation.scanner;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.*; import java.lang.annotation.*;
import java.util.ArrayList; import java.util.ArrayList;
@ -16,32 +16,32 @@ public class MateAnnotationScannerTest {
@Test @Test
public void supportTest() { public void supportTest() {
AnnotationScanner scanner = new MetaAnnotationScanner(); AnnotationScanner scanner = new MetaAnnotationScanner();
Assert.assertTrue(scanner.support(AnnotationForScannerTest.class)); assertTrue(scanner.support(AnnotationForScannerTest.class));
Assert.assertFalse(scanner.support(ReflectUtil.getField(Example.class, "id"))); assertFalse(scanner.support(ReflectUtil.getField(Example.class, "id")));
Assert.assertFalse(scanner.support(ReflectUtil.getMethod(Example.class, "getId"))); assertFalse(scanner.support(ReflectUtil.getMethod(Example.class, "getId")));
Assert.assertFalse(scanner.support(null)); assertFalse(scanner.support(null));
Assert.assertFalse(scanner.support(Example.class)); assertFalse(scanner.support(Example.class));
} }
@Test @Test
public void getAnnotationsTest() { public void getAnnotationsTest() {
AnnotationScanner scanner = new MetaAnnotationScanner(); AnnotationScanner scanner = new MetaAnnotationScanner();
Assert.assertTrue(scanner.support(AnnotationForScannerTest3.class)); assertTrue(scanner.support(AnnotationForScannerTest3.class));
Map<Class<? extends Annotation>, Annotation> annotations = CollUtil.toMap(scanner.getAnnotations(AnnotationForScannerTest3.class), new HashMap<>(), Annotation::annotationType); Map<Class<? extends Annotation>, Annotation> annotations = CollUtil.toMap(scanner.getAnnotations(AnnotationForScannerTest3.class), new HashMap<>(), Annotation::annotationType);
Assert.assertEquals(3, annotations.size()); assertEquals(3, annotations.size());
Assert.assertTrue(annotations.containsKey(AnnotationForScannerTest.class)); assertTrue(annotations.containsKey(AnnotationForScannerTest.class));
Assert.assertTrue(annotations.containsKey(AnnotationForScannerTest1.class)); assertTrue(annotations.containsKey(AnnotationForScannerTest1.class));
Assert.assertTrue(annotations.containsKey(AnnotationForScannerTest2.class)); assertTrue(annotations.containsKey(AnnotationForScannerTest2.class));
Assert.assertFalse(annotations.containsKey(AnnotationForScannerTest3.class)); assertFalse(annotations.containsKey(AnnotationForScannerTest3.class));
scanner = new MetaAnnotationScanner(false); scanner = new MetaAnnotationScanner(false);
Assert.assertTrue(scanner.support(AnnotationForScannerTest3.class)); assertTrue(scanner.support(AnnotationForScannerTest3.class));
annotations = CollUtil.toMap(scanner.getAnnotations(AnnotationForScannerTest3.class), new HashMap<>(), Annotation::annotationType); annotations = CollUtil.toMap(scanner.getAnnotations(AnnotationForScannerTest3.class), new HashMap<>(), Annotation::annotationType);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
Assert.assertTrue(annotations.containsKey(AnnotationForScannerTest2.class)); assertTrue(annotations.containsKey(AnnotationForScannerTest2.class));
Assert.assertFalse(annotations.containsKey(AnnotationForScannerTest.class)); assertFalse(annotations.containsKey(AnnotationForScannerTest.class));
Assert.assertFalse(annotations.containsKey(AnnotationForScannerTest1.class)); assertFalse(annotations.containsKey(AnnotationForScannerTest1.class));
Assert.assertFalse(annotations.containsKey(AnnotationForScannerTest3.class)); assertFalse(annotations.containsKey(AnnotationForScannerTest3.class));
} }
@Test @Test
@ -53,15 +53,15 @@ public class MateAnnotationScannerTest {
AnnotationForScannerTest3.class, null AnnotationForScannerTest3.class, null
); );
Assert.assertEquals(3, map.size()); assertEquals(3, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals(AnnotationForScannerTest2.class, map.get(0).get(0).annotationType()); assertEquals(AnnotationForScannerTest2.class, map.get(0).get(0).annotationType());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals(AnnotationForScannerTest1.class, map.get(1).get(0).annotationType()); assertEquals(AnnotationForScannerTest1.class, map.get(1).get(0).annotationType());
Assert.assertEquals(1, map.get(2).size()); assertEquals(1, map.get(2).size());
Assert.assertEquals(AnnotationForScannerTest.class, map.get(2).get(0).annotationType()); assertEquals(AnnotationForScannerTest.class, map.get(2).get(0).annotationType());
} }
static class Example { static class Example {

View File

@ -3,8 +3,8 @@ package cn.hutool.core.annotation.scanner;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.lang.reflect.Method; import java.lang.reflect.Method;
@ -15,45 +15,45 @@ public class MethodAnnotationScannerTest {
@Test @Test
public void supportTest() { public void supportTest() {
AnnotationScanner scanner = new MethodAnnotationScanner(); AnnotationScanner scanner = new MethodAnnotationScanner();
Assert.assertTrue(scanner.support(ReflectUtil.getMethod(Example.class, "test"))); assertTrue(scanner.support(ReflectUtil.getMethod(Example.class, "test")));
Assert.assertFalse(scanner.support(null)); assertFalse(scanner.support(null));
Assert.assertFalse(scanner.support(Example.class)); assertFalse(scanner.support(Example.class));
Assert.assertFalse(scanner.support(ReflectUtil.getField(Example.class, "id"))); assertFalse(scanner.support(ReflectUtil.getField(Example.class, "id")));
} }
@Test @Test
public void getAnnotationsTest() { public void getAnnotationsTest() {
AnnotationScanner scanner = new MethodAnnotationScanner(); AnnotationScanner scanner = new MethodAnnotationScanner();
Method method = ReflectUtil.getMethod(Example.class, "test"); Method method = ReflectUtil.getMethod(Example.class, "test");
Assert.assertNotNull(method); assertNotNull(method);
// 不查找父类中具有相同方法签名的方法 // 不查找父类中具有相同方法签名的方法
List<Annotation> annotations = scanner.getAnnotations(method); List<Annotation> annotations = scanner.getAnnotations(method);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
Assert.assertEquals(CollUtil.getFirst(annotations).annotationType(), AnnotationForScannerTest.class); assertEquals(CollUtil.getFirst(annotations).annotationType(), AnnotationForScannerTest.class);
// 查找父类中具有相同方法签名的方法 // 查找父类中具有相同方法签名的方法
scanner = new MethodAnnotationScanner(true); scanner = new MethodAnnotationScanner(true);
annotations = scanner.getAnnotations(method); annotations = scanner.getAnnotations(method);
Assert.assertEquals(3, annotations.size()); assertEquals(3, annotations.size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) annotations.get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) annotations.get(0)).value());
Assert.assertEquals("SuperClass", ((AnnotationForScannerTest) annotations.get(1)).value()); assertEquals("SuperClass", ((AnnotationForScannerTest) annotations.get(1)).value());
Assert.assertEquals("SuperInterface", ((AnnotationForScannerTest) annotations.get(2)).value()); assertEquals("SuperInterface", ((AnnotationForScannerTest) annotations.get(2)).value());
// 查找父类中具有相同方法签名的方法但是不查找SuperInterface // 查找父类中具有相同方法签名的方法但是不查找SuperInterface
scanner = new MethodAnnotationScanner(true).addExcludeTypes(SuperInterface.class); scanner = new MethodAnnotationScanner(true).addExcludeTypes(SuperInterface.class);
annotations = scanner.getAnnotations(method); annotations = scanner.getAnnotations(method);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) annotations.get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) annotations.get(0)).value());
Assert.assertEquals("SuperClass", ((AnnotationForScannerTest) annotations.get(1)).value()); assertEquals("SuperClass", ((AnnotationForScannerTest) annotations.get(1)).value());
// 查找父类中具有相同方法签名的方法但是只查找SuperClass // 查找父类中具有相同方法签名的方法但是只查找SuperClass
scanner = new MethodAnnotationScanner(true) scanner = new MethodAnnotationScanner(true)
.setFilter(t -> ClassUtil.isAssignable(SuperClass.class, t)); .setFilter(t -> ClassUtil.isAssignable(SuperClass.class, t));
annotations = scanner.getAnnotations(method); annotations = scanner.getAnnotations(method);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) annotations.get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) annotations.get(0)).value());
Assert.assertEquals("SuperClass", ((AnnotationForScannerTest) annotations.get(1)).value()); assertEquals("SuperClass", ((AnnotationForScannerTest) annotations.get(1)).value());
} }
@Test @Test
@ -66,8 +66,8 @@ public class MethodAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
method, null method, null
); );
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
// 查找父类中具有相同方法签名的方法 // 查找父类中具有相同方法签名的方法
map.clear(); map.clear();
@ -75,13 +75,13 @@ public class MethodAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
method, null method, null
); );
Assert.assertEquals(3, map.size()); assertEquals(3, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals("SuperClass", ((AnnotationForScannerTest) map.get(1).get(0)).value()); assertEquals("SuperClass", ((AnnotationForScannerTest) map.get(1).get(0)).value());
Assert.assertEquals(1, map.get(2).size()); assertEquals(1, map.get(2).size());
Assert.assertEquals("SuperInterface", ((AnnotationForScannerTest) map.get(2).get(0)).value()); assertEquals("SuperInterface", ((AnnotationForScannerTest) map.get(2).get(0)).value());
// 查找父类中具有相同方法签名的方法但是不查找SuperInterface // 查找父类中具有相同方法签名的方法但是不查找SuperInterface
map.clear(); map.clear();
@ -91,11 +91,11 @@ public class MethodAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
method, null method, null
); );
Assert.assertEquals(2, map.size()); assertEquals(2, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals("SuperClass", ((AnnotationForScannerTest) map.get(1).get(0)).value()); assertEquals("SuperClass", ((AnnotationForScannerTest) map.get(1).get(0)).value());
// 查找父类中具有相同方法签名的方法但是只查找SuperClass // 查找父类中具有相同方法签名的方法但是只查找SuperClass
map.clear(); map.clear();
@ -105,11 +105,11 @@ public class MethodAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
method, null method, null
); );
Assert.assertEquals(2, map.size()); assertEquals(2, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals("SuperClass", ((AnnotationForScannerTest) map.get(1).get(0)).value()); assertEquals("SuperClass", ((AnnotationForScannerTest) map.get(1).get(0)).value());
} }
static class Example extends SuperClass { static class Example extends SuperClass {

View File

@ -2,8 +2,8 @@ package cn.hutool.core.annotation.scanner;
import cn.hutool.core.util.ClassUtil; import cn.hutool.core.util.ClassUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.lang.annotation.Annotation; import java.lang.annotation.Annotation;
import java.util.ArrayList; import java.util.ArrayList;
@ -16,42 +16,42 @@ public class TypeAnnotationScannerTest {
@Test @Test
public void supportTest() { public void supportTest() {
AnnotationScanner scanner = new TypeAnnotationScanner(); AnnotationScanner scanner = new TypeAnnotationScanner();
Assert.assertTrue(scanner.support(Example.class)); assertTrue(scanner.support(Example.class));
Assert.assertFalse(scanner.support(ReflectUtil.getField(Example.class, "id"))); assertFalse(scanner.support(ReflectUtil.getField(Example.class, "id")));
Assert.assertFalse(scanner.support(ReflectUtil.getMethod(Example.class, "getId"))); assertFalse(scanner.support(ReflectUtil.getMethod(Example.class, "getId")));
Assert.assertFalse(scanner.support(null)); assertFalse(scanner.support(null));
} }
@Test @Test
public void getAnnotationsTest() { public void getAnnotationsTest() {
AnnotationScanner scanner = new TypeAnnotationScanner(); AnnotationScanner scanner = new TypeAnnotationScanner();
List<Annotation> annotations = scanner.getAnnotations(Example.class); List<Annotation> annotations = scanner.getAnnotations(Example.class);
Assert.assertEquals(3, annotations.size()); assertEquals(3, annotations.size());
annotations.forEach(a -> Assert.assertEquals(a.annotationType(), AnnotationForScannerTest.class)); annotations.forEach(a -> assertEquals(a.annotationType(), AnnotationForScannerTest.class));
// 不查找父接口 // 不查找父接口
scanner = new TypeAnnotationScanner().setIncludeInterfaces(false); scanner = new TypeAnnotationScanner().setIncludeInterfaces(false);
annotations = scanner.getAnnotations(Example.class); annotations = scanner.getAnnotations(Example.class);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
annotations.forEach(a -> Assert.assertEquals(a.annotationType(), AnnotationForScannerTest.class)); annotations.forEach(a -> assertEquals(a.annotationType(), AnnotationForScannerTest.class));
// 不查找父类 // 不查找父类
scanner = new TypeAnnotationScanner().setIncludeSuperClass(false); scanner = new TypeAnnotationScanner().setIncludeSuperClass(false);
annotations = scanner.getAnnotations(Example.class); annotations = scanner.getAnnotations(Example.class);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
annotations.forEach(a -> Assert.assertEquals(a.annotationType(), AnnotationForScannerTest.class)); annotations.forEach(a -> assertEquals(a.annotationType(), AnnotationForScannerTest.class));
// 不查找ExampleSupplerClass.class // 不查找ExampleSupplerClass.class
scanner = new TypeAnnotationScanner().addExcludeTypes(ExampleSupplerClass.class); scanner = new TypeAnnotationScanner().addExcludeTypes(ExampleSupplerClass.class);
annotations = scanner.getAnnotations(Example.class); annotations = scanner.getAnnotations(Example.class);
Assert.assertEquals(1, annotations.size()); assertEquals(1, annotations.size());
annotations.forEach(a -> Assert.assertEquals(a.annotationType(), AnnotationForScannerTest.class)); annotations.forEach(a -> assertEquals(a.annotationType(), AnnotationForScannerTest.class));
// 只查找ExampleSupplerClass.class // 只查找ExampleSupplerClass.class
scanner = new TypeAnnotationScanner().setFilter(t -> ClassUtil.isAssignable(ExampleSupplerClass.class, t)); scanner = new TypeAnnotationScanner().setFilter(t -> ClassUtil.isAssignable(ExampleSupplerClass.class, t));
annotations = scanner.getAnnotations(Example.class); annotations = scanner.getAnnotations(Example.class);
Assert.assertEquals(2, annotations.size()); assertEquals(2, annotations.size());
annotations.forEach(a -> Assert.assertEquals(a.annotationType(), AnnotationForScannerTest.class)); annotations.forEach(a -> assertEquals(a.annotationType(), AnnotationForScannerTest.class));
} }
@Test @Test
@ -63,13 +63,13 @@ public class TypeAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
Example.class, null Example.class, null
); );
Assert.assertEquals(3, map.size()); assertEquals(3, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals("ExampleSupplerClass", ((AnnotationForScannerTest) map.get(1).get(0)).value()); assertEquals("ExampleSupplerClass", ((AnnotationForScannerTest) map.get(1).get(0)).value());
Assert.assertEquals(1, map.get(2).size()); assertEquals(1, map.get(2).size());
Assert.assertEquals("ExampleInterface", ((AnnotationForScannerTest) map.get(2).get(0)).value()); assertEquals("ExampleInterface", ((AnnotationForScannerTest) map.get(2).get(0)).value());
// 不查找父接口 // 不查找父接口
map.clear(); map.clear();
@ -79,11 +79,11 @@ public class TypeAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
Example.class, null Example.class, null
); );
Assert.assertEquals(2, map.size()); assertEquals(2, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals("ExampleSupplerClass", ((AnnotationForScannerTest) map.get(1).get(0)).value()); assertEquals("ExampleSupplerClass", ((AnnotationForScannerTest) map.get(1).get(0)).value());
// 不查找父类 // 不查找父类
map.clear(); map.clear();
@ -93,9 +93,9 @@ public class TypeAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
Example.class, null Example.class, null
); );
Assert.assertEquals(1, map.size()); assertEquals(1, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
// 不查找ExampleSupplerClass.class // 不查找ExampleSupplerClass.class
map.clear(); map.clear();
@ -105,9 +105,9 @@ public class TypeAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
Example.class, null Example.class, null
); );
Assert.assertEquals(1, map.size()); assertEquals(1, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
// 只查找ExampleSupplerClass.class // 只查找ExampleSupplerClass.class
map.clear(); map.clear();
@ -117,11 +117,11 @@ public class TypeAnnotationScannerTest {
(index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation), (index, annotation) -> map.computeIfAbsent(index, i -> new ArrayList<>()).add(annotation),
Example.class, null Example.class, null
); );
Assert.assertEquals(2, map.size()); assertEquals(2, map.size());
Assert.assertEquals(1, map.get(0).size()); assertEquals(1, map.get(0).size());
Assert.assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value()); assertEquals("Example", ((AnnotationForScannerTest) map.get(0).get(0)).value());
Assert.assertEquals(1, map.get(1).size()); assertEquals(1, map.get(1).size());
Assert.assertEquals("ExampleSupplerClass", ((AnnotationForScannerTest) map.get(1).get(0)).value()); assertEquals("ExampleSupplerClass", ((AnnotationForScannerTest) map.get(1).get(0)).value());
} }
@AnnotationForScannerTest("ExampleSupplerClass") @AnnotationForScannerTest("ExampleSupplerClass")

View File

@ -4,8 +4,8 @@ import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import lombok.Builder; import lombok.Builder;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class BeanCopyMappingTest { public class BeanCopyMappingTest {
@ -24,7 +24,7 @@ public class BeanCopyMappingTest {
BeanUtil.copyProperties(b, a, copyOptions); BeanUtil.copyProperties(b, a, copyOptions);
BeanUtil.copyProperties(a, c); BeanUtil.copyProperties(a, c);
Assert.assertEquals("12312312", c.getCarNo()); assertEquals("12312312", c.getCarNo());
} }
@Data @Data

View File

@ -1,8 +1,8 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* {@link BeanDesc} 单元测试类 * {@link BeanDesc} 单元测试类
@ -15,13 +15,13 @@ public class BeanDescTest {
@Test @Test
public void propDescTes() { public void propDescTes() {
BeanDesc desc = BeanUtil.getBeanDesc(User.class); BeanDesc desc = BeanUtil.getBeanDesc(User.class);
Assert.assertEquals("User", desc.getSimpleName()); assertEquals("User", desc.getSimpleName());
Assert.assertEquals("age", desc.getField("age").getName()); assertEquals("age", desc.getField("age").getName());
Assert.assertEquals("getAge", desc.getGetter("age").getName()); assertEquals("getAge", desc.getGetter("age").getName());
Assert.assertEquals("setAge", desc.getSetter("age").getName()); assertEquals("setAge", desc.getSetter("age").getName());
Assert.assertEquals(1, desc.getSetter("age").getParameterTypes().length); assertEquals(1, desc.getSetter("age").getParameterTypes().length);
Assert.assertSame(int.class, desc.getSetter("age").getParameterTypes()[0]); assertSame(int.class, desc.getSetter("age").getParameterTypes()[0]);
} }
@ -30,29 +30,29 @@ public class BeanDescTest {
BeanDesc desc = BeanUtil.getBeanDesc(User.class); BeanDesc desc = BeanUtil.getBeanDesc(User.class);
PropDesc prop = desc.getProp("name"); PropDesc prop = desc.getProp("name");
Assert.assertEquals("name", prop.getFieldName()); assertEquals("name", prop.getFieldName());
Assert.assertEquals("getName", prop.getGetter().getName()); assertEquals("getName", prop.getGetter().getName());
Assert.assertEquals("setName", prop.getSetter().getName()); assertEquals("setName", prop.getSetter().getName());
Assert.assertEquals(1, prop.getSetter().getParameterTypes().length); assertEquals(1, prop.getSetter().getParameterTypes().length);
Assert.assertSame(String.class, prop.getSetter().getParameterTypes()[0]); assertSame(String.class, prop.getSetter().getParameterTypes()[0]);
} }
@Test @Test
public void propDescOfBooleanTest() { public void propDescOfBooleanTest() {
BeanDesc desc = BeanUtil.getBeanDesc(User.class); BeanDesc desc = BeanUtil.getBeanDesc(User.class);
Assert.assertEquals("isAdmin", desc.getGetter("isAdmin").getName()); assertEquals("isAdmin", desc.getGetter("isAdmin").getName());
Assert.assertEquals("setAdmin", desc.getSetter("isAdmin").getName()); assertEquals("setAdmin", desc.getSetter("isAdmin").getName());
Assert.assertEquals("isGender", desc.getGetter("gender").getName()); assertEquals("isGender", desc.getGetter("gender").getName());
Assert.assertEquals("setGender", desc.getSetter("gender").getName()); assertEquals("setGender", desc.getSetter("gender").getName());
} }
@Test @Test
public void propDescOfBooleanTest2() { public void propDescOfBooleanTest2() {
BeanDesc desc = BeanUtil.getBeanDesc(User.class); BeanDesc desc = BeanUtil.getBeanDesc(User.class);
Assert.assertEquals("isIsSuper", desc.getGetter("isSuper").getName()); assertEquals("isIsSuper", desc.getGetter("isSuper").getName());
Assert.assertEquals("setIsSuper", desc.getSetter("isSuper").getName()); assertEquals("setIsSuper", desc.getSetter("isSuper").getName());
} }
@Test @Test
@ -61,19 +61,19 @@ public class BeanDescTest {
User user = new User(); User user = new User();
desc.getProp("name").setValue(user, "张三"); desc.getProp("name").setValue(user, "张三");
Assert.assertEquals("张三", user.getName()); assertEquals("张三", user.getName());
Object value = desc.getProp("name").getValue(user); Object value = desc.getProp("name").getValue(user);
Assert.assertEquals("张三", value); assertEquals("张三", value);
} }
@Test @Test
@Ignore @Disabled
public void propDescOfBooleanTest3() { public void propDescOfBooleanTest3() {
BeanDesc desc = BeanUtil.getBeanDesc(User.class); BeanDesc desc = BeanUtil.getBeanDesc(User.class);
Assert.assertEquals("setLastPage", desc.getSetter("lastPage").getName()); assertEquals("setLastPage", desc.getSetter("lastPage").getName());
Assert.assertEquals("setIsLastPage", desc.getSetter("isLastPage").getName()); assertEquals("setIsLastPage", desc.getSetter("isLastPage").getName());
} }
public static class User { public static class User {

View File

@ -4,15 +4,16 @@ import cn.hutool.core.lang.test.bean.ExamInfoDict;
import cn.hutool.core.lang.test.bean.UserInfoDict; import cn.hutool.core.lang.test.bean.UserInfoDict;
import cn.hutool.core.util.ArrayUtil; import cn.hutool.core.util.ArrayUtil;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import org.junit.jupiter.api.BeforeEach;
import org.junit.Before; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.HashMap; import java.util.HashMap;
import java.util.List; import java.util.List;
import java.util.Map; import java.util.Map;
import static org.junit.jupiter.api.Assertions.assertEquals;
/** /**
* {@link BeanPath} 单元测试 * {@link BeanPath} 单元测试
* *
@ -22,7 +23,7 @@ public class BeanPathTest {
Map<String, Object> tempMap; Map<String, Object> tempMap;
@Before @BeforeEach
public void init() { public void init() {
// ------------------------------------------------- 考试信息列表 // ------------------------------------------------- 考试信息列表
final ExamInfoDict examInfoDict = new ExamInfoDict(); final ExamInfoDict examInfoDict = new ExamInfoDict();
@ -60,36 +61,36 @@ public class BeanPathTest {
@Test @Test
public void beanPathTest1() { public void beanPathTest1() {
final BeanPath pattern = new BeanPath("userInfo.examInfoDict[0].id"); final BeanPath pattern = new BeanPath("userInfo.examInfoDict[0].id");
Assert.assertEquals("userInfo", pattern.patternParts.get(0)); assertEquals("userInfo", pattern.patternParts.get(0));
Assert.assertEquals("examInfoDict", pattern.patternParts.get(1)); assertEquals("examInfoDict", pattern.patternParts.get(1));
Assert.assertEquals("0", pattern.patternParts.get(2)); assertEquals("0", pattern.patternParts.get(2));
Assert.assertEquals("id", pattern.patternParts.get(3)); assertEquals("id", pattern.patternParts.get(3));
} }
@Test @Test
public void beanPathTest2() { public void beanPathTest2() {
final BeanPath pattern = new BeanPath("[userInfo][examInfoDict][0][id]"); final BeanPath pattern = new BeanPath("[userInfo][examInfoDict][0][id]");
Assert.assertEquals("userInfo", pattern.patternParts.get(0)); assertEquals("userInfo", pattern.patternParts.get(0));
Assert.assertEquals("examInfoDict", pattern.patternParts.get(1)); assertEquals("examInfoDict", pattern.patternParts.get(1));
Assert.assertEquals("0", pattern.patternParts.get(2)); assertEquals("0", pattern.patternParts.get(2));
Assert.assertEquals("id", pattern.patternParts.get(3)); assertEquals("id", pattern.patternParts.get(3));
} }
@Test @Test
public void beanPathTest3() { public void beanPathTest3() {
final BeanPath pattern = new BeanPath("['userInfo']['examInfoDict'][0]['id']"); final BeanPath pattern = new BeanPath("['userInfo']['examInfoDict'][0]['id']");
Assert.assertEquals("userInfo", pattern.patternParts.get(0)); assertEquals("userInfo", pattern.patternParts.get(0));
Assert.assertEquals("examInfoDict", pattern.patternParts.get(1)); assertEquals("examInfoDict", pattern.patternParts.get(1));
Assert.assertEquals("0", pattern.patternParts.get(2)); assertEquals("0", pattern.patternParts.get(2));
Assert.assertEquals("id", pattern.patternParts.get(3)); assertEquals("id", pattern.patternParts.get(3));
} }
@Test @Test
public void getTest() { public void getTest() {
final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id"); final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
final Object result = pattern.get(tempMap); final Object result = pattern.get(tempMap);
Assert.assertEquals(1, result); assertEquals(1, result);
} }
@Test @Test
@ -97,15 +98,15 @@ public class BeanPathTest {
final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id"); final BeanPath pattern = BeanPath.create("userInfo.examInfoDict[0].id");
pattern.set(tempMap, 2); pattern.set(tempMap, 2);
final Object result = pattern.get(tempMap); final Object result = pattern.get(tempMap);
Assert.assertEquals(2, result); assertEquals(2, result);
} }
@Test @Test
public void getMapTest() { public void getMapTest() {
final BeanPath pattern = BeanPath.create("userInfo[id, photoPath]"); final BeanPath pattern = BeanPath.create("userInfo[id, photoPath]");
@SuppressWarnings("unchecked") final Map<String, Object> result = (Map<String, Object>) pattern.get(tempMap); @SuppressWarnings("unchecked") final Map<String, Object> result = (Map<String, Object>) pattern.get(tempMap);
Assert.assertEquals(1, result.get("id")); assertEquals(1, result.get("id"));
Assert.assertEquals("yx.mm.com", result.get("photoPath")); assertEquals("yx.mm.com", result.get("photoPath"));
} }
@Test @Test
@ -114,17 +115,17 @@ public class BeanPathTest {
BeanPath beanPath = BeanPath.create("list[0].name"); BeanPath beanPath = BeanPath.create("list[0].name");
beanPath.set(map, "张三"); beanPath.set(map, "张三");
Assert.assertEquals("{list=[{name=张三}]}", map.toString()); assertEquals("{list=[{name=张三}]}", map.toString());
map.clear(); map.clear();
beanPath = BeanPath.create("list[1].name"); beanPath = BeanPath.create("list[1].name");
beanPath.set(map, "张三"); beanPath.set(map, "张三");
Assert.assertEquals("{list=[null, {name=张三}]}", map.toString()); assertEquals("{list=[null, {name=张三}]}", map.toString());
map.clear(); map.clear();
beanPath = BeanPath.create("list[0].1.name"); beanPath = BeanPath.create("list[0].1.name");
beanPath.set(map, "张三"); beanPath.set(map, "张三");
Assert.assertEquals("{list=[[null, {name=张三}]]}", map.toString()); assertEquals("{list=[[null, {name=张三}]]}", map.toString());
} }
@Test @Test
@ -135,7 +136,7 @@ public class BeanPathTest {
BeanPath.create("hobby[1]").set(myUser, "KFC"); BeanPath.create("hobby[1]").set(myUser, "KFC");
BeanPath.create("hobby[2]").set(myUser, "COFFE"); BeanPath.create("hobby[2]").set(myUser, "COFFE");
Assert.assertEquals("[LOL, KFC, COFFE]", ArrayUtil.toString(myUser.getHobby())); assertEquals("[LOL, KFC, COFFE]", ArrayUtil.toString(myUser.getHobby()));
} }
@Data @Data

View File

@ -5,7 +5,6 @@ import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.bean.copier.ValueProvider; import cn.hutool.core.bean.copier.ValueProvider;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.lang.Console;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapBuilder; import cn.hutool.core.map.MapBuilder;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
@ -15,9 +14,8 @@ import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.*; import lombok.*;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import org.junit.Assert; import org.junit.jupiter.api.Disabled;
import org.junit.Ignore; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.beans.PropertyDescriptor; import java.beans.PropertyDescriptor;
import java.io.Serializable; import java.io.Serializable;
@ -27,6 +25,8 @@ import java.time.LocalDateTime;
import java.util.*; import java.util.*;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* Bean工具单元测试 * Bean工具单元测试
* *
@ -39,7 +39,7 @@ public class BeanUtilTest {
// HashMap不包含setXXX方法不是bean // HashMap不包含setXXX方法不是bean
final boolean isBean = BeanUtil.isBean(HashMap.class); final boolean isBean = BeanUtil.isBean(HashMap.class);
Assert.assertFalse(isBean); assertFalse(isBean);
} }
@Test @Test
@ -65,21 +65,21 @@ public class BeanUtilTest {
}, CopyOptions.create()); }, CopyOptions.create());
Assert.assertEquals("张三", person.getName()); assertEquals("张三", person.getName());
Assert.assertEquals(18, person.getAge()); assertEquals(18, person.getAge());
} }
@Test @Test
public void fillBeanWithMapIgnoreCaseTest() { public void fillBeanWithMapIgnoreCaseTest() {
final Map<String, Object> map = MapBuilder.<String, Object>create() final Map<String, Object> map = MapBuilder.<String, Object>create()
.put("Name", "Joe") .put("Name", "Joe")
.put("aGe", 12) .put("aGe", 12)
.put("openId", "DFDFSDFWERWER") .put("openId", "DFDFSDFWERWER")
.build(); .build();
final SubPerson person = BeanUtil.fillBeanWithMapIgnoreCase(map, new SubPerson(), false); final SubPerson person = BeanUtil.fillBeanWithMapIgnoreCase(map, new SubPerson(), false);
Assert.assertEquals("Joe", person.getName()); assertEquals("Joe", person.getName());
Assert.assertEquals(12, person.getAge()); assertEquals(12, person.getAge());
Assert.assertEquals("DFDFSDFWERWER", person.getOpenid()); assertEquals("DFDFSDFWERWER", person.getOpenid());
} }
@Test @Test
@ -91,11 +91,11 @@ public class BeanUtilTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
final Map<?, ?> map = BeanUtil.toBean(person, Map.class); final Map<?, ?> map = BeanUtil.toBean(person, Map.class);
Assert.assertEquals("测试A11", map.get("name")); assertEquals("测试A11", map.get("name"));
Assert.assertEquals(14, map.get("age")); assertEquals(14, map.get("age"));
Assert.assertEquals("11213232", map.get("openid")); assertEquals("11213232", map.get("openid"));
// static属性应被忽略 // static属性应被忽略
Assert.assertFalse(map.containsKey("SUBNAME")); assertFalse(map.containsKey("SUBNAME"));
} }
/** /**
@ -109,9 +109,9 @@ public class BeanUtilTest {
map.put("age", "aaaaaa"); map.put("age", "aaaaaa");
final Person person = BeanUtil.toBeanIgnoreError(map, Person.class); final Person person = BeanUtil.toBeanIgnoreError(map, Person.class);
Assert.assertEquals("Joe", person.getName()); assertEquals("Joe", person.getName());
// 错误的类型不copy这个字段使用对象创建的默认值 // 错误的类型不copy这个字段使用对象创建的默认值
Assert.assertEquals(0, person.getAge()); assertEquals(0, person.getAge());
} }
@Test @Test
@ -121,8 +121,8 @@ public class BeanUtilTest {
map.put("aGe", 12); map.put("aGe", 12);
final Person person = BeanUtil.toBeanIgnoreCase(map, Person.class, false); final Person person = BeanUtil.toBeanIgnoreCase(map, Person.class, false);
Assert.assertEquals("Joe", person.getName()); assertEquals("Joe", person.getName());
Assert.assertEquals(12, person.getAge()); assertEquals(12, person.getAge());
} }
@Test @Test
@ -137,8 +137,8 @@ public class BeanUtilTest {
mapping.put("b_age", "age"); mapping.put("b_age", "age");
final Person person = BeanUtil.toBean(map, Person.class, CopyOptions.create().setFieldMapping(mapping)); final Person person = BeanUtil.toBean(map, Person.class, CopyOptions.create().setFieldMapping(mapping));
Assert.assertEquals("Joe", person.getName()); assertEquals("Joe", person.getName());
Assert.assertEquals(12, person.getAge()); assertEquals(12, person.getAge());
} }
/** /**
@ -152,18 +152,20 @@ public class BeanUtilTest {
// 非空构造也可以实例化成功 // 非空构造也可以实例化成功
final Person2 person = BeanUtil.toBean(map, Person2.class, CopyOptions.create()); final Person2 person = BeanUtil.toBean(map, Person2.class, CopyOptions.create());
Assert.assertEquals("Joe", person.name); assertEquals("Joe", person.name);
Assert.assertEquals(12, person.age); assertEquals(12, person.age);
} }
/** /**
* 测试在不忽略错误情况下转换失败需要报错 * 测试在不忽略错误情况下转换失败需要报错
*/ */
@Test(expected = NumberFormatException.class) @Test
public void mapToBeanWinErrorTest() { public void mapToBeanWinErrorTest() {
final Map<String, String> map = new HashMap<>(); assertThrows(NumberFormatException.class, () -> {
map.put("age", "哈哈"); final Map<String, String> map = new HashMap<>();
BeanUtil.toBean(map, Person.class); map.put("age", "哈哈");
BeanUtil.toBean(map, Person.class);
});
} }
@Test @Test
@ -176,11 +178,11 @@ public class BeanUtilTest {
final Map<String, Object> map = BeanUtil.beanToMap(person); final Map<String, Object> map = BeanUtil.beanToMap(person);
Assert.assertEquals("测试A11", map.get("name")); assertEquals("测试A11", map.get("name"));
Assert.assertEquals(14, map.get("age")); assertEquals(14, map.get("age"));
Assert.assertEquals("11213232", map.get("openid")); assertEquals("11213232", map.get("openid"));
// static属性应被忽略 // static属性应被忽略
Assert.assertFalse(map.containsKey("SUBNAME")); assertFalse(map.containsKey("SUBNAME"));
} }
@Test @Test
@ -193,11 +195,11 @@ public class BeanUtilTest {
final Map<String, Object> map = BeanUtil.beanToMap(person, (String[]) null); final Map<String, Object> map = BeanUtil.beanToMap(person, (String[]) null);
Assert.assertEquals("测试A11", map.get("name")); assertEquals("测试A11", map.get("name"));
Assert.assertEquals(14, map.get("age")); assertEquals(14, map.get("age"));
Assert.assertEquals("11213232", map.get("openid")); assertEquals("11213232", map.get("openid"));
// static属性应被忽略 // static属性应被忽略
Assert.assertFalse(map.containsKey("SUBNAME")); assertFalse(map.containsKey("SUBNAME"));
} }
@Test @Test
@ -209,7 +211,7 @@ public class BeanUtilTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
final Map<String, Object> map = BeanUtil.beanToMap(person, true, true); final Map<String, Object> map = BeanUtil.beanToMap(person, true, true);
Assert.assertEquals("sub名字", map.get("sub_name")); assertEquals("sub名字", map.get("sub_name"));
} }
@Test @Test
@ -221,8 +223,8 @@ public class BeanUtilTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
final Map<String, Object> map = BeanUtil.beanToMap(person, new LinkedHashMap<>(), final Map<String, Object> map = BeanUtil.beanToMap(person, new LinkedHashMap<>(),
CopyOptions.create().setFieldValueEditor((key, value) -> key + "_" + value)); CopyOptions.create().setFieldValueEditor((key, value) -> key + "_" + value));
Assert.assertEquals("subName_sub名字", map.get("subName")); assertEquals("subName_sub名字", map.get("subName"));
} }
@Test @Test
@ -237,7 +239,7 @@ public class BeanUtilTest {
person.setBooleanb(true); person.setBooleanb(true);
final Map<String, Object> map = BeanUtil.beanToMap(person); final Map<String, Object> map = BeanUtil.beanToMap(person);
Assert.assertEquals("sub名字", map.get("aliasSubName")); assertEquals("sub名字", map.get("aliasSubName"));
} }
@Test @Test
@ -249,11 +251,11 @@ public class BeanUtilTest {
map.put("is_booleanb", true); map.put("is_booleanb", true);
final SubPersonWithAlias subPersonWithAlias = BeanUtil.toBean(map, SubPersonWithAlias.class); final SubPersonWithAlias subPersonWithAlias = BeanUtil.toBean(map, SubPersonWithAlias.class);
Assert.assertEquals("sub名字", subPersonWithAlias.getSubName()); assertEquals("sub名字", subPersonWithAlias.getSubName());
//https://gitee.com/dromara/hutool/issues/I6H0XF //https://gitee.com/dromara/hutool/issues/I6H0XF
Assert.assertFalse(subPersonWithAlias.isBooleana()); assertFalse(subPersonWithAlias.isBooleana());
Assert.assertNull(subPersonWithAlias.getBooleanb()); assertNull(subPersonWithAlias.getBooleanb());
} }
@Test @Test
@ -269,8 +271,8 @@ public class BeanUtilTest {
person.setDate2(now.toLocalDate()); person.setDate2(now.toLocalDate());
final Map<String, Object> map = BeanUtil.beanToMap(person, false, true); final Map<String, Object> map = BeanUtil.beanToMap(person, false, true);
Assert.assertEquals(now, map.get("date")); assertEquals(now, map.get("date"));
Assert.assertEquals(now.toLocalDate(), map.get("date2")); assertEquals(now.toLocalDate(), map.get("date2"));
} }
@Test @Test
@ -282,16 +284,16 @@ public class BeanUtilTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
final Object name = BeanUtil.getProperty(person, "name"); final Object name = BeanUtil.getProperty(person, "name");
Assert.assertEquals("测试A11", name); assertEquals("测试A11", name);
final Object subName = BeanUtil.getProperty(person, "subName"); final Object subName = BeanUtil.getProperty(person, "subName");
Assert.assertEquals("sub名字", subName); assertEquals("sub名字", subName);
} }
@Test @Test
@SuppressWarnings("ConstantConditions") @SuppressWarnings("ConstantConditions")
public void getNullPropertyTest() { public void getNullPropertyTest() {
final Object property = BeanUtil.getProperty(null, "name"); final Object property = BeanUtil.getProperty(null, "name");
Assert.assertNull(property); assertNull(property);
} }
@Test @Test
@ -301,12 +303,12 @@ public class BeanUtilTest {
for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) { for (final PropertyDescriptor propertyDescriptor : propertyDescriptors) {
set.add(propertyDescriptor.getName()); set.add(propertyDescriptor.getName());
} }
Assert.assertTrue(set.contains("age")); assertTrue(set.contains("age"));
Assert.assertTrue(set.contains("id")); assertTrue(set.contains("id"));
Assert.assertTrue(set.contains("name")); assertTrue(set.contains("name"));
Assert.assertTrue(set.contains("openid")); assertTrue(set.contains("openid"));
Assert.assertTrue(set.contains("slow")); assertTrue(set.contains("slow"));
Assert.assertTrue(set.contains("subName")); assertTrue(set.contains("subName"));
} }
@Test @Test
@ -318,15 +320,15 @@ public class BeanUtilTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
final SubPerson person1 = BeanUtil.copyProperties(person, SubPerson.class); final SubPerson person1 = BeanUtil.copyProperties(person, SubPerson.class);
Assert.assertEquals(14, person1.getAge()); assertEquals(14, person1.getAge());
Assert.assertEquals("11213232", person1.getOpenid()); assertEquals("11213232", person1.getOpenid());
Assert.assertEquals("测试A11", person1.getName()); assertEquals("测试A11", person1.getName());
Assert.assertEquals("sub名字", person1.getSubName()); assertEquals("sub名字", person1.getSubName());
} }
@Test @Test
@Ignore @Disabled
public void multiThreadTest(){ public void multiThreadTest() {
final Student student = new Student(); final Student student = new Student();
student.setName("张三"); student.setName("张三");
student.setAge(123); student.setAge(123);
@ -339,8 +341,8 @@ public class BeanUtilTest {
final List<Student> studentList = ListUtil.of(student, student2); final List<Student> studentList = ListUtil.of(student, student2);
for (int i=0;i<5000;i++){ for (int i = 0; i < 5000; i++) {
new Thread(()->{ new Thread(() -> {
final List<Student> list = ObjectUtil.clone(studentList); final List<Student> list = ObjectUtil.clone(studentList);
final List<Student> listReps = list.stream().map(s1 -> { final List<Student> listReps = list.stream().map(s1 -> {
final Student s2 = new Student(); final Student s2 = new Student();
@ -363,12 +365,12 @@ public class BeanUtilTest {
// 测试boolean参数值isXXX形式 // 测试boolean参数值isXXX形式
final SubPerson p2 = new SubPerson(); final SubPerson p2 = new SubPerson();
BeanUtil.copyProperties(p1, p2); BeanUtil.copyProperties(p1, p2);
Assert.assertTrue(p2.getSlow()); assertTrue(p2.getSlow());
// 测试boolean参数值非isXXX形式 // 测试boolean参数值非isXXX形式
final SubPerson2 p3 = new SubPerson2(); final SubPerson2 p3 = new SubPerson2();
BeanUtil.copyProperties(p1, p3); BeanUtil.copyProperties(p1, p3);
Assert.assertTrue(p3.getSlow()); assertTrue(p3.getSlow());
} }
@Test @Test
@ -382,11 +384,11 @@ public class BeanUtilTest {
// null值不覆盖目标属性 // null值不覆盖目标属性
BeanUtil.copyProperties(p1, p2, CopyOptions.create().ignoreNullValue()); BeanUtil.copyProperties(p1, p2, CopyOptions.create().ignoreNullValue());
Assert.assertEquals("oldName", p2.getName()); assertEquals("oldName", p2.getName());
// null覆盖目标属性 // null覆盖目标属性
BeanUtil.copyProperties(p1, p2); BeanUtil.copyProperties(p1, p2);
Assert.assertNull(p2.getName()); assertNull(p2.getName());
} }
@Test @Test
@ -399,9 +401,9 @@ public class BeanUtilTest {
final Map<String, Object> map = MapUtil.newHashMap(); final Map<String, Object> map = MapUtil.newHashMap();
BeanUtil.copyProperties(p1, map); BeanUtil.copyProperties(p1, map);
Assert.assertTrue((Boolean) map.get("slow")); assertTrue((Boolean) map.get("slow"));
Assert.assertEquals("测试", map.get("name")); assertEquals("测试", map.get("name"));
Assert.assertEquals("sub测试", map.get("subName")); assertEquals("sub测试", map.get("subName"));
} }
@Test @Test
@ -414,9 +416,9 @@ public class BeanUtilTest {
final Map<String, Object> map = MapUtil.newHashMap(); final Map<String, Object> map = MapUtil.newHashMap();
BeanUtil.copyProperties(p1, map); BeanUtil.copyProperties(p1, map);
Assert.assertTrue((Boolean) map.get("isSlow")); assertTrue((Boolean) map.get("isSlow"));
Assert.assertEquals("测试", map.get("name")); assertEquals("测试", map.get("name"));
Assert.assertEquals("sub测试", map.get("subName")); assertEquals("sub测试", map.get("subName"));
} }
@Test @Test
@ -429,9 +431,9 @@ public class BeanUtilTest {
final Map<String, Object> map = MapUtil.newHashMap(); final Map<String, Object> map = MapUtil.newHashMap();
BeanUtil.copyProperties(p1, map, CopyOptions.create().setIgnoreNullValue(true)); BeanUtil.copyProperties(p1, map, CopyOptions.create().setIgnoreNullValue(true));
Assert.assertTrue((Boolean) map.get("isSlow")); assertTrue((Boolean) map.get("isSlow"));
Assert.assertEquals("测试", map.get("name")); assertEquals("测试", map.get("name"));
Assert.assertFalse(map.containsKey("subName")); assertFalse(map.containsKey("subName"));
} }
@Test @Test
@ -443,8 +445,8 @@ public class BeanUtilTest {
final Person person2 = BeanUtil.trimStrFields(person); final Person person2 = BeanUtil.trimStrFields(person);
// 是否改变原对象 // 是否改变原对象
Assert.assertEquals("张三", person.getName()); assertEquals("张三", person.getName());
Assert.assertEquals("张三", person2.getName()); assertEquals("张三", person2.getName());
} }
// ----------------------------------------------------------------------------------------------------------------- // -----------------------------------------------------------------------------------------------------------------
@ -529,9 +531,9 @@ public class BeanUtilTest {
final SubPersonWithOverlayTransientField dest = new SubPersonWithOverlayTransientField(); final SubPersonWithOverlayTransientField dest = new SubPersonWithOverlayTransientField();
BeanUtil.copyProperties(source, dest); BeanUtil.copyProperties(source, dest);
Assert.assertEquals(source.getName(), dest.getName()); assertEquals(source.getName(), dest.getName());
Assert.assertEquals(source.getAge(), dest.getAge()); assertEquals(source.getAge(), dest.getAge());
Assert.assertEquals(source.getOpenid(), dest.getOpenid()); assertEquals(source.getOpenid(), dest.getOpenid());
} }
@Test @Test
@ -562,8 +564,8 @@ public class BeanUtilTest {
info.setCode("123"); info.setCode("123");
final HllFoodEntity entity = new HllFoodEntity(); final HllFoodEntity entity = new HllFoodEntity();
BeanUtil.copyProperties(info, entity); BeanUtil.copyProperties(info, entity);
Assert.assertEquals(info.getBookID(), entity.getBookId()); assertEquals(info.getBookID(), entity.getBookId());
Assert.assertEquals(info.getCode(), entity.getCode2()); assertEquals(info.getCode(), entity.getCode2());
} }
@Test @Test
@ -572,13 +574,13 @@ public class BeanUtilTest {
info.setBookID("0"); info.setBookID("0");
info.setCode("123"); info.setCode("123");
final Food newFood = BeanUtil.copyProperties(info, Food.class, "code"); final Food newFood = BeanUtil.copyProperties(info, Food.class, "code");
Assert.assertEquals(info.getBookID(), newFood.getBookID()); assertEquals(info.getBookID(), newFood.getBookID());
Assert.assertNull(newFood.getCode()); assertNull(newFood.getCode());
} }
@Test @Test
public void copyNullTest() { public void copyNullTest() {
Assert.assertNull(BeanUtil.copyProperties(null, Food.class)); assertNull(BeanUtil.copyProperties(null, Food.class));
} }
@Test @Test
@ -589,8 +591,8 @@ public class BeanUtilTest {
final Food newFood = new Food(); final Food newFood = new Food();
final CopyOptions copyOptions = CopyOptions.create().setPropertiesFilter((f, v) -> !(v instanceof CharSequence) || StrUtil.isNotBlank(v.toString())); final CopyOptions copyOptions = CopyOptions.create().setPropertiesFilter((f, v) -> !(v instanceof CharSequence) || StrUtil.isNotBlank(v.toString()));
BeanUtil.copyProperties(info, newFood, copyOptions); BeanUtil.copyProperties(info, newFood, copyOptions);
Assert.assertEquals(info.getBookID(), newFood.getBookID()); assertEquals(info.getBookID(), newFood.getBookID());
Assert.assertNull(newFood.getCode()); assertNull(newFood.getCode());
} }
@Test @Test
@ -601,13 +603,13 @@ public class BeanUtilTest {
o.setAge(123); o.setAge(123);
o.setOpenid("asd"); o.setOpenid("asd");
@SuppressWarnings("unchecked") final CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(Person::getAge,Person::getOpenid); @SuppressWarnings("unchecked") final CopyOptions copyOptions = CopyOptions.create().setIgnoreProperties(Person::getAge, Person::getOpenid);
final Person n = new Person(); final Person n = new Person();
BeanUtil.copyProperties(o, n, copyOptions); BeanUtil.copyProperties(o, n, copyOptions);
// 是否忽略拷贝属性 // 是否忽略拷贝属性
Assert.assertNotEquals(o.getAge(),n.getAge()); assertNotEquals(o.getAge(), n.getAge());
Assert.assertNotEquals(o.getOpenid(),n.getOpenid()); assertNotEquals(o.getOpenid(), n.getOpenid());
} }
@Data @Data
@ -630,7 +632,7 @@ public class BeanUtilTest {
public void setPropertiesTest() { public void setPropertiesTest() {
final Map<String, Object> resultMap = MapUtil.newHashMap(); final Map<String, Object> resultMap = MapUtil.newHashMap();
BeanUtil.setProperty(resultMap, "codeList[0].name", "张三"); BeanUtil.setProperty(resultMap, "codeList[0].name", "张三");
Assert.assertEquals("{codeList=[{name=张三}]}", resultMap.toString()); assertEquals("{codeList=[{name=张三}]}", resultMap.toString());
} }
@Test @Test
@ -641,7 +643,7 @@ public class BeanUtilTest {
final Station station2 = new Station(); final Station station2 = new Station();
BeanUtil.copyProperties(station, station2); BeanUtil.copyProperties(station, station2);
Assert.assertEquals(new Long(123456L), station2.getId()); assertEquals(new Long(123456L), station2.getId());
} }
enum Version { enum Version {
@ -660,19 +662,22 @@ public class BeanUtilTest {
final Vto v1 = new Vto(); final Vto v1 = new Vto();
v1.setVersions(EnumSet.allOf(Version.class)); v1.setVersions(EnumSet.allOf(Version.class));
final Vto v2 = BeanUtil.copyProperties(v1, Vto.class); final Vto v2 = BeanUtil.copyProperties(v1, Vto.class);
Assert.assertNotNull(v2); assertNotNull(v2);
Assert.assertNotNull(v2.getVersions()); assertNotNull(v2.getVersions());
} }
@Test @Test
public void enumSetTest() { public void enumSetTest() {
final Collection<Version> objects = CollUtil.create(EnumSet.class, Version.class); final Collection<Version> objects = CollUtil.create(EnumSet.class, Version.class);
Assert.assertNotNull(objects); assertNotNull(objects);
Assert.assertTrue(EnumSet.class.isAssignableFrom(objects.getClass())); assertTrue(EnumSet.class.isAssignableFrom(objects.getClass()));
} }
static class Station extends Tree<Long> {} static class Station extends Tree<Long> {
static class Tree<T> extends Entity<T> {} }
static class Tree<T> extends Entity<T> {
}
@Data @Data
public static class Entity<T> { public static class Entity<T> {
@ -694,10 +699,10 @@ public class BeanUtilTest {
final List<Student> studentList = ListUtil.of(student, student2); final List<Student> studentList = ListUtil.of(student, student2);
final List<Person> people = BeanUtil.copyToList(studentList, Person.class); final List<Person> people = BeanUtil.copyToList(studentList, Person.class);
Assert.assertEquals(studentList.size(), people.size()); assertEquals(studentList.size(), people.size());
for (int i = 0; i < studentList.size(); i++) { for (int i = 0; i < studentList.size(); i++) {
Assert.assertEquals(studentList.get(i).getName(), people.get(i).getName()); assertEquals(studentList.get(i).getName(), people.get(i).getName());
Assert.assertEquals(studentList.get(i).getAge(), people.get(i).getAge()); assertEquals(studentList.get(i).getAge(), people.get(i).getAge());
} }
} }
@ -713,11 +718,11 @@ public class BeanUtilTest {
a.setSortOrder(9L); a.setSortOrder(9L);
final Map<String, Object> f = BeanUtil.beanToMap( final Map<String, Object> f = BeanUtil.beanToMap(
a, a,
new LinkedHashMap<>(), new LinkedHashMap<>(),
false, false,
key -> Arrays.asList("id", "name", "code", "sortOrder").contains(key) ? key : null); key -> Arrays.asList("id", "name", "code", "sortOrder").contains(key) ? key : null);
Assert.assertFalse(f.containsKey(null)); assertFalse(f.containsKey(null));
} }
@Data @Data
@ -748,8 +753,8 @@ public class BeanUtilTest {
final BeanPath beanPath = BeanPath.create("testPojo2List.age"); final BeanPath beanPath = BeanPath.create("testPojo2List.age");
final Object o = beanPath.get(testPojo); final Object o = beanPath.get(testPojo);
Assert.assertEquals(Integer.valueOf(2), ArrayUtil.get(o, 0)); assertEquals(Integer.valueOf(2), ArrayUtil.get(o, 0));
Assert.assertEquals(Integer.valueOf(3), ArrayUtil.get(o, 1)); assertEquals(Integer.valueOf(3), ArrayUtil.get(o, 1));
} }
@Data @Data
@ -764,7 +769,7 @@ public class BeanUtilTest {
} }
@Data @Data
public static class Student implements Serializable{ public static class Student implements Serializable {
private static final long serialVersionUID = 1L; private static final long serialVersionUID = 1L;
String name; String name;
@ -774,8 +779,8 @@ public class BeanUtilTest {
/** /**
* @author dazer * @author dazer
* copyProperties(Object source, Object target, CopyOptions copyOptions) * copyProperties(Object source, Object target, CopyOptions copyOptions)
* copyOptions的 setFieldNameEditor 不为空的时候有bug,这里进行修复 * copyOptions的 setFieldNameEditor 不为空的时候有bug,这里进行修复
*/ */
@Test @Test
public void beanToBeanCopyOptionsTest() { public void beanToBeanCopyOptionsTest() {
@ -786,17 +791,17 @@ public class BeanUtilTest {
childVo1.setChild_mother_name("赵敏敏"); childVo1.setChild_mother_name("赵敏敏");
final CopyOptions copyOptions = CopyOptions.create(). final CopyOptions copyOptions = CopyOptions.create().
//setIgnoreNullValue(true). //setIgnoreNullValue(true).
//setIgnoreCase(false). //setIgnoreCase(false).
setFieldNameEditor(StrUtil::toCamelCase); setFieldNameEditor(StrUtil::toCamelCase);
final ChildVo2 childVo2 = new ChildVo2(); final ChildVo2 childVo2 = new ChildVo2();
BeanUtil.copyProperties(childVo1, childVo2, copyOptions); BeanUtil.copyProperties(childVo1, childVo2, copyOptions);
Assert.assertEquals(childVo1.getChild_address(), childVo2.getChildAddress()); assertEquals(childVo1.getChild_address(), childVo2.getChildAddress());
Assert.assertEquals(childVo1.getChild_name(), childVo2.getChildName()); assertEquals(childVo1.getChild_name(), childVo2.getChildName());
Assert.assertEquals(childVo1.getChild_father_name(), childVo2.getChildFatherName()); assertEquals(childVo1.getChild_father_name(), childVo2.getChildFatherName());
Assert.assertEquals(childVo1.getChild_mother_name(), childVo2.getChildMotherName()); assertEquals(childVo1.getChild_mother_name(), childVo2.getChildMotherName());
} }
@Data @Data
@ -816,11 +821,11 @@ public class BeanUtilTest {
} }
@Test @Test
public void issueI41WKPTest(){ public void issueI41WKPTest() {
final Test1 t1 = new Test1().setStrList(ListUtil.toList("list")); final Test1 t1 = new Test1().setStrList(ListUtil.toList("list"));
final Test2 t2_hu = new Test2(); final Test2 t2_hu = new Test2();
BeanUtil.copyProperties(t1, t2_hu, CopyOptions.create().setIgnoreError(true)); BeanUtil.copyProperties(t1, t2_hu, CopyOptions.create().setIgnoreError(true));
Assert.assertNull(t2_hu.getStrList()); assertNull(t2_hu.getStrList());
} }
@Data @Data
@ -836,33 +841,35 @@ public class BeanUtilTest {
} }
@Test @Test
public void issuesI53O9JTest(){ public void issuesI53O9JTest() {
final Map<String, String> map = new HashMap<>(); final Map<String, String> map = new HashMap<>();
map.put("statusIdUpdateTime", ""); map.put("statusIdUpdateTime", "");
final WkCrmCustomer customer = new WkCrmCustomer(); final WkCrmCustomer customer = new WkCrmCustomer();
BeanUtil.copyProperties(map, customer); BeanUtil.copyProperties(map, customer);
Assert.assertNull(customer.getStatusIdUpdateTime()); assertNull(customer.getStatusIdUpdateTime());
} }
@Data @Data
public static class WkCrmCustomer{ public static class WkCrmCustomer {
private LocalDateTime statusIdUpdateTime; private LocalDateTime statusIdUpdateTime;
} }
@Test @Test
public void valueProviderToBeanTest(){ public void valueProviderToBeanTest() {
// https://gitee.com/dromara/hutool/issues/I5B4R7 // https://gitee.com/dromara/hutool/issues/I5B4R7
final CopyOptions copyOptions = CopyOptions.create(); final CopyOptions copyOptions = CopyOptions.create();
final Map<String, String> filedMap= new HashMap<>(); final Map<String, String> filedMap = new HashMap<>();
filedMap.put("name", "sourceId"); filedMap.put("name", "sourceId");
copyOptions.setFieldMapping(filedMap); copyOptions.setFieldMapping(filedMap);
final TestPojo pojo = BeanUtil.toBean(TestPojo.class, new ValueProvider<String>() { final TestPojo pojo = BeanUtil.toBean(TestPojo.class, new ValueProvider<String>() {
final HashMap<String, Object> map = new HashMap<>(); final HashMap<String, Object> map = new HashMap<>();
{ {
map.put("sourceId", "123"); map.put("sourceId", "123");
} }
@Override @Override
public Object value(final String key, final Type valueType) { public Object value(final String key, final Type valueType) {
return map.get(key); return map.get(key);
@ -873,7 +880,7 @@ public class BeanUtilTest {
return map.containsKey(key); return map.containsKey(key);
} }
}, copyOptions); }, copyOptions);
Assert.assertEquals("123", pojo.getName()); assertEquals("123", pojo.getName());
} }
@Data @Data
@ -895,6 +902,7 @@ public class BeanUtilTest {
private Integer sex; private Integer sex;
private String mobile; private String mobile;
} }
@Test @Test
public void isCommonFieldsEqualTest() { public void isCommonFieldsEqualTest() {
final TestUserEntity userEntity = new TestUserEntity(); final TestUserEntity userEntity = new TestUserEntity();
@ -907,30 +915,30 @@ public class BeanUtilTest {
BeanUtil.copyProperties(userDTO, userEntity); BeanUtil.copyProperties(userDTO, userEntity);
Assert.assertTrue(BeanUtil.isCommonFieldsEqual(userDTO, userEntity)); assertTrue(BeanUtil.isCommonFieldsEqual(userDTO, userEntity));
userEntity.setAge(13); userEntity.setAge(13);
Assert.assertFalse(BeanUtil.isCommonFieldsEqual(userDTO, userEntity)); assertFalse(BeanUtil.isCommonFieldsEqual(userDTO, userEntity));
Assert.assertTrue(BeanUtil.isCommonFieldsEqual(userDTO, userEntity, "age")); assertTrue(BeanUtil.isCommonFieldsEqual(userDTO, userEntity, "age"));
Assert.assertTrue(BeanUtil.isCommonFieldsEqual(null, null)); assertTrue(BeanUtil.isCommonFieldsEqual(null, null));
Assert.assertFalse(BeanUtil.isCommonFieldsEqual(null, userEntity)); assertFalse(BeanUtil.isCommonFieldsEqual(null, userEntity));
Assert.assertFalse(BeanUtil.isCommonFieldsEqual(userEntity, null)); assertFalse(BeanUtil.isCommonFieldsEqual(userEntity, null));
userEntity.setSex(0); userEntity.setSex(0);
Assert.assertTrue(BeanUtil.isCommonFieldsEqual(userDTO, userEntity, "age", "sex")); assertTrue(BeanUtil.isCommonFieldsEqual(userDTO, userEntity, "age", "sex"));
} }
@Test @Test
public void hasGetterTest() { public void hasGetterTest() {
// https://gitee.com/dromara/hutool/issues/I6M7Z7 // https://gitee.com/dromara/hutool/issues/I6M7Z7
final boolean b = BeanUtil.hasGetter(Object.class); final boolean b = BeanUtil.hasGetter(Object.class);
Assert.assertFalse(b); assertFalse(b);
} }
@Test @Test
public void issueI9VTZGTest() { public void issueI9VTZGTest() {
final boolean bean = BeanUtil.isBean(Dict.class); final boolean bean = BeanUtil.isBean(Dict.class);
Assert.assertFalse(bean); assertFalse(bean);
} }
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* {@link DynaBean}单元测试 * {@link DynaBean}单元测试
@ -19,18 +19,18 @@ public class DynaBeanTest {
bean.set("age", 12); bean.set("age", 12);
String name = bean.get("name"); String name = bean.get("name");
Assert.assertEquals(user.getName(), name); assertEquals(user.getName(), name);
int age = bean.get("age"); int age = bean.get("age");
Assert.assertEquals(user.getAge(), age); assertEquals(user.getAge(), age);
//重复包装测试 //重复包装测试
DynaBean bean2 = new DynaBean(bean); DynaBean bean2 = new DynaBean(bean);
User user2 = bean2.getBean(); User user2 = bean2.getBean();
Assert.assertEquals(user, user2); assertEquals(user, user2);
//执行指定方法 //执行指定方法
Object invoke = bean2.invoke("testMethod"); Object invoke = bean2.invoke("testMethod");
Assert.assertEquals("test for 李华", invoke); assertEquals("test for 李华", invoke);
} }
@ -43,19 +43,19 @@ public class DynaBeanTest {
bean.set("age", age_before); bean.set("age", age_before);
String name_after = bean.get("name"); String name_after = bean.get("name");
Assert.assertEquals(name_before, name_after); assertEquals(name_before, name_after);
int age_after = bean.get("age"); int age_after = bean.get("age");
Assert.assertEquals(age_before, age_after); assertEquals(age_before, age_after);
//重复包装测试 //重复包装测试
DynaBean bean2 = new DynaBean(bean); DynaBean bean2 = new DynaBean(bean);
User user2 = bean2.getBean(); User user2 = bean2.getBean();
User user1 = bean.getBean(); User user1 = bean.getBean();
Assert.assertEquals(user1, user2); assertEquals(user1, user2);
//执行指定方法 //执行指定方法
Object invoke = bean2.invoke("testMethod"); Object invoke = bean2.invoke("testMethod");
Assert.assertEquals("test for 李华", invoke); assertEquals("test for 李华", invoke);
} }
@ -68,19 +68,19 @@ public class DynaBeanTest {
bean.set("age", age_before); bean.set("age", age_before);
String name_after = bean.get("name"); String name_after = bean.get("name");
Assert.assertEquals(name_before, name_after); assertEquals(name_before, name_after);
int age_after = bean.get("age"); int age_after = bean.get("age");
Assert.assertEquals(age_before, age_after); assertEquals(age_before, age_after);
//重复包装测试 //重复包装测试
DynaBean bean2 = new DynaBean(bean); DynaBean bean2 = new DynaBean(bean);
User user2 = bean2.getBean(); User user2 = bean2.getBean();
User user1 = bean.getBean(); User user1 = bean.getBean();
Assert.assertEquals(user1, user2); assertEquals(user1, user2);
//执行指定方法 //执行指定方法
Object invoke = bean2.invoke("testMethod"); Object invoke = bean2.invoke("testMethod");
Assert.assertEquals("test for 李华", invoke); assertEquals("test for 李华", invoke);
} }
@Data @Data

View File

@ -4,8 +4,8 @@ import cn.hutool.core.annotation.Alias;
import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.Serializable; import java.io.Serializable;
@ -22,8 +22,8 @@ public class Issue1687Test {
final SysUser sysUser = BeanUtil.toBean(sysUserFb, SysUser.class); final SysUser sysUser = BeanUtil.toBean(sysUserFb, SysUser.class);
// 别名错位导致找不到字段 // 别名错位导致找不到字段
Assert.assertNull(sysUser.getDepart()); assertNull(sysUser.getDepart());
Assert.assertEquals(new Long(456L), sysUser.getOrgId()); assertEquals(new Long(456L), sysUser.getOrgId());
} }
@Test @Test
@ -38,8 +38,8 @@ public class Issue1687Test {
); );
final SysUser sysUser = BeanUtil.toBean(sysUserFb, SysUser.class, copyOptions); final SysUser sysUser = BeanUtil.toBean(sysUserFb, SysUser.class, copyOptions);
Assert.assertEquals(new Long(123L), sysUser.getDepart()); assertEquals(new Long(123L), sysUser.getDepart());
Assert.assertEquals(new Long(456L), sysUser.getOrgId()); assertEquals(new Long(456L), sysUser.getOrgId());
} }
@Data @Data

View File

@ -1,7 +1,7 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* https://github.com/dromara/hutool/issues/2009 * https://github.com/dromara/hutool/issues/2009
@ -71,6 +71,6 @@ public class Issue2009Test {
A a = new A(); A a = new A();
BeanUtil.copyProperties(b, a); BeanUtil.copyProperties(b, a);
Assert.assertEquals(b.getPapss(), a.getPapss()); assertEquals(b.getPapss(), a.getPapss());
} }
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* https://github.com/dromara/hutool/issues/2082<br> * https://github.com/dromara/hutool/issues/2082<br>
@ -14,7 +14,7 @@ public class Issue2082Test {
public void toBeanTest() { public void toBeanTest() {
TestBean2 testBean2 = new TestBean2(); TestBean2 testBean2 = new TestBean2();
TestBean test = BeanUtil.toBean(testBean2, TestBean.class); TestBean test = BeanUtil.toBean(testBean2, TestBean.class);
Assert.assertNull(test.getId()); assertNull(test.getId());
} }
@Data @Data

View File

@ -3,8 +3,8 @@ package cn.hutool.core.bean;
import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.text.NamingCase; import cn.hutool.core.text.NamingCase;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -24,10 +24,10 @@ public class Issue2202Test {
ResponseSignVerifyParams case1 = BeanUtil.toBean(headerMap, ResponseSignVerifyParams.class, ResponseSignVerifyParams case1 = BeanUtil.toBean(headerMap, ResponseSignVerifyParams.class,
CopyOptions.create().setFieldNameEditor(field -> NamingCase.toCamelCase(field, '-'))); CopyOptions.create().setFieldNameEditor(field -> NamingCase.toCamelCase(field, '-')));
Assert.assertEquals("serial", case1.getWechatpaySerial()); assertEquals("serial", case1.getWechatpaySerial());
Assert.assertEquals("nonce", case1.getWechatpayNonce()); assertEquals("nonce", case1.getWechatpayNonce());
Assert.assertEquals("timestamp", case1.getWechatpayTimestamp()); assertEquals("timestamp", case1.getWechatpayTimestamp());
Assert.assertEquals("signature", case1.getWechatpaySignature()); assertEquals("signature", case1.getWechatpaySignature());
} }
@Data @Data

View File

@ -1,8 +1,8 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -21,7 +21,7 @@ public class Issue2697Test {
final Map<String, String> mapB = new HashMap<>(16); final Map<String, String> mapB = new HashMap<>(16);
BeanUtil.copyProperties(mapA, mapB, "12"); BeanUtil.copyProperties(mapA, mapB, "12");
Assert.assertEquals(2, mapB.size()); assertEquals(2, mapB.size());
Assert.assertFalse(mapB.containsKey("12")); assertFalse(mapB.containsKey("12"));
} }
} }

View File

@ -12,8 +12,8 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -24,6 +24,6 @@ public class Issue3091Test {
public void copyToListTest() { public void copyToListTest() {
final List<Long> list = Arrays.asList(1L,2L); final List<Long> list = Arrays.asList(1L,2L);
final List<Integer> result = BeanUtil.copyToList(list, Integer.class); final List<Integer> result = BeanUtil.copyToList(list, Integer.class);
Assert.assertEquals("[1, 2]", result.toString()); assertEquals("[1, 2]", result.toString());
} }
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.bean;
import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -17,8 +17,8 @@ public class Issue3452Test {
properties.put("user_age", 25); properties.put("user_age", 25);
final User user = BeanUtil.fillBeanWithMap( final User user = BeanUtil.fillBeanWithMap(
properties, new User(), CopyOptions.create()); properties, new User(), CopyOptions.create());
Assert.assertEquals("JohnDoe", user.getName()); assertEquals("JohnDoe", user.getName());
Assert.assertEquals(25, user.getUserAge()); assertEquals(25, user.getUserAge());
} }
@Data @Data

View File

@ -3,8 +3,8 @@ package cn.hutool.core.bean;
import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.bean.copier.CopyOptions;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Map; import java.util.Map;
@ -13,6 +13,6 @@ public class Issue3497Test {
public void mapToMapTest() { public void mapToMapTest() {
final Map<String, String> aB = MapUtil.builder("a_b", "1").build(); final Map<String, String> aB = MapUtil.builder("a_b", "1").build();
final Map<?, ?> bean = BeanUtil.toBean(aB, Map.class, CopyOptions.create().setFieldNameEditor(StrUtil::toCamelCase)); final Map<?, ?> bean = BeanUtil.toBean(aB, Map.class, CopyOptions.create().setFieldNameEditor(StrUtil::toCamelCase));
Assert.assertEquals(bean.toString(), "{aB=1}"); assertEquals(bean.toString(), "{aB=1}");
} }
} }

View File

@ -1,12 +1,12 @@
package cn.hutool.core.bean; package cn.hutool.core.bean;
import lombok.Data; import lombok.Data;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
import static org.junit.Assert.assertNotNull; import static org.junit.jupiter.api.Assertions.assertNotNull;
public class Issue3645Test { public class Issue3645Test {
@Test @Test

View File

@ -2,8 +2,8 @@ package cn.hutool.core.bean;
import cn.hutool.core.bean.copier.CopyOptions; import cn.hutool.core.bean.copier.CopyOptions;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class IssueI80FP4Test { public class IssueI80FP4Test {
@Test @Test
@ -15,7 +15,7 @@ public class IssueI80FP4Test {
final Dest dest = new Dest(); final Dest dest = new Dest();
final CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreCase(true).setIgnoreProperties("enderDest"); final CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreCase(true).setIgnoreProperties("enderDest");
BeanUtil.copyProperties(sourceDest, dest, copyOptions); BeanUtil.copyProperties(sourceDest, dest, copyOptions);
Assert.assertNull(dest.getEnderDest()); assertNull(dest.getEnderDest());
} }
@Test @Test
@ -27,7 +27,7 @@ public class IssueI80FP4Test {
final Dest dest = new Dest(); final Dest dest = new Dest();
final CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreCase(true).setIgnoreProperties("enderdest"); final CopyOptions copyOptions = CopyOptions.create().setIgnoreNullValue(true).setIgnoreCase(true).setIgnoreProperties("enderdest");
BeanUtil.copyProperties(sourceDest, dest, copyOptions); BeanUtil.copyProperties(sourceDest, dest, copyOptions);
Assert.assertNull(dest.getEnderDest()); assertNull(dest.getEnderDest());
} }
@Data @Data

View File

@ -3,8 +3,8 @@ package cn.hutool.core.bean;
import cn.hutool.core.annotation.Alias; import cn.hutool.core.annotation.Alias;
import lombok.Data; import lombok.Data;
import lombok.Setter; import lombok.Setter;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class IssueI8JASOTest { public class IssueI8JASOTest {
@ -14,7 +14,7 @@ public class IssueI8JASOTest {
userOne.setEmail("123@qq.com"); userOne.setEmail("123@qq.com");
final UserTwo userTwo = new UserTwo(); final UserTwo userTwo = new UserTwo();
BeanUtil.copyProperties(userOne, userTwo); BeanUtil.copyProperties(userOne, userTwo);
Assert.assertEquals(userOne.getEmail(), userTwo.getEmail()); assertEquals(userOne.getEmail(), userTwo.getEmail());
} }
@Data @Data

View File

@ -1,8 +1,8 @@
package cn.hutool.core.bean.copier; package cn.hutool.core.bean.copier;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
@ -13,14 +13,14 @@ public class BeanCopierTest {
final A a = new A(); final A a = new A();
HashMap<Object, Object> map = BeanCopier.create(a, new HashMap<>(), CopyOptions.create()).copy(); HashMap<Object, Object> map = BeanCopier.create(a, new HashMap<>(), CopyOptions.create()).copy();
Assert.assertEquals(1, map.size()); assertEquals(1, map.size());
Assert.assertTrue(map.containsKey("value")); assertTrue(map.containsKey("value"));
Assert.assertNull(map.get("value")); assertNull(map.get("value"));
// 忽略null的情况下空字段不写入map // 忽略null的情况下空字段不写入map
map = BeanCopier.create(a, new HashMap<>(), CopyOptions.create().ignoreNullValue()).copy(); map = BeanCopier.create(a, new HashMap<>(), CopyOptions.create().ignoreNullValue()).copy();
Assert.assertFalse(map.containsKey("value")); assertFalse(map.containsKey("value"));
Assert.assertEquals(0, map.size()); assertEquals(0, map.size());
} }
/** /**
@ -36,7 +36,7 @@ public class BeanCopierTest {
final BeanCopier<B> copier = BeanCopier.create(a, b, CopyOptions.create().setOverride(false)); final BeanCopier<B> copier = BeanCopier.create(a, b, CopyOptions.create().setOverride(false));
copier.copy(); copier.copy();
Assert.assertEquals("abc", b.getValue()); assertEquals("abc", b.getValue());
} }
/** /**
@ -52,7 +52,7 @@ public class BeanCopierTest {
final BeanCopier<B> copier = BeanCopier.create(a, b, CopyOptions.create()); final BeanCopier<B> copier = BeanCopier.create(a, b, CopyOptions.create());
copier.copy(); copier.copy();
Assert.assertEquals("123", b.getValue()); assertEquals("123", b.getValue());
} }
/** /**
@ -67,12 +67,12 @@ public class BeanCopierTest {
BeanCopier<B> copier = BeanCopier.create(a, b, CopyOptions.create().setOverride(false)); BeanCopier<B> copier = BeanCopier.create(a, b, CopyOptions.create().setOverride(false));
copier.copy(); copier.copy();
Assert.assertEquals("123", b.getValue()); assertEquals("123", b.getValue());
b.setValue(null); b.setValue(null);
copier = BeanCopier.create(a, b, CopyOptions.create().setOverride(false)); copier = BeanCopier.create(a, b, CopyOptions.create().setOverride(false));
copier.copy(); copier.copy();
Assert.assertEquals("abc", b.getValue()); assertEquals("abc", b.getValue());
} }
@Data @Data

View File

@ -1,8 +1,8 @@
package cn.hutool.core.bean.copier; package cn.hutool.core.bean.copier;
import lombok.Setter; import lombok.Setter;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -16,7 +16,7 @@ public class Issue2718Test {
.create(deployment, new LinkedHashMap<String, Object>(), CopyOptions.create().setIgnoreProperties("resources")) .create(deployment, new LinkedHashMap<String, Object>(), CopyOptions.create().setIgnoreProperties("resources"))
.copy(); .copy();
Assert.assertTrue(target.isEmpty()); assertTrue(target.isEmpty());
} }
@Test @Test
@ -27,7 +27,7 @@ public class Issue2718Test {
.create(deployment, new Deployment(), CopyOptions.create().setIgnoreProperties("resources")) .create(deployment, new Deployment(), CopyOptions.create().setIgnoreProperties("resources"))
.copy(); .copy();
Assert.assertNull(target.resources); assertNull(target.resources);
} }
@Setter @Setter

View File

@ -5,8 +5,8 @@ import lombok.Getter;
import lombok.Setter; import lombok.Setter;
import lombok.ToString; import lombok.ToString;
import lombok.experimental.Accessors; import lombok.experimental.Accessors;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.Map; import java.util.Map;
@ -29,11 +29,11 @@ public class GenericBuilderTest {
.with(Box::setHeight, 7) .with(Box::setHeight, 7)
.build(); .build();
Assert.assertEquals(1024L, box.getId().longValue()); assertEquals(1024L, box.getId().longValue());
Assert.assertEquals("Hello World!", box.getTitle()); assertEquals("Hello World!", box.getTitle());
Assert.assertEquals(9, box.getLength().intValue()); assertEquals(9, box.getLength().intValue());
Assert.assertEquals(8, box.getWidth().intValue()); assertEquals(8, box.getWidth().intValue());
Assert.assertEquals(7, box.getHeight().intValue()); assertEquals(7, box.getHeight().intValue());
// 对象修改 // 对象修改
Box boxModified = GenericBuilder Box boxModified = GenericBuilder
@ -44,11 +44,11 @@ public class GenericBuilderTest {
.with(Box::setHeight, 5) .with(Box::setHeight, 5)
.build(); .build();
Assert.assertEquals(1024L, boxModified.getId().longValue()); assertEquals(1024L, boxModified.getId().longValue());
Assert.assertEquals("Hello Friend!", box.getTitle()); assertEquals("Hello Friend!", box.getTitle());
Assert.assertEquals(3, boxModified.getLength().intValue()); assertEquals(3, boxModified.getLength().intValue());
Assert.assertEquals(4, boxModified.getWidth().intValue()); assertEquals(4, boxModified.getWidth().intValue());
Assert.assertEquals(5, boxModified.getHeight().intValue()); assertEquals(5, boxModified.getHeight().intValue());
// 多参数构造 // 多参数构造
Box box1 = GenericBuilder Box box1 = GenericBuilder
@ -56,12 +56,12 @@ public class GenericBuilderTest {
.with(Box::alis) .with(Box::alis)
.build(); .build();
Assert.assertEquals(2048L, box1.getId().longValue()); assertEquals(2048L, box1.getId().longValue());
Assert.assertEquals("Hello Partner!", box1.getTitle()); assertEquals("Hello Partner!", box1.getTitle());
Assert.assertEquals(222, box1.getLength().intValue()); assertEquals(222, box1.getLength().intValue());
Assert.assertEquals(333, box1.getWidth().intValue()); assertEquals(333, box1.getWidth().intValue());
Assert.assertEquals(444, box1.getHeight().intValue()); assertEquals(444, box1.getHeight().intValue());
Assert.assertEquals("TomXin:\"Hello Partner!\"", box1.getTitleAlias()); assertEquals("TomXin:\"Hello Partner!\"", box1.getTitleAlias());
} }
@Test @Test
@ -73,9 +73,9 @@ public class GenericBuilderTest {
.with(Map::put, "yellow", "#FFFF00") .with(Map::put, "yellow", "#FFFF00")
.with(Map::put, "blue", "#0000FF") .with(Map::put, "blue", "#0000FF")
.build(); .build();
Assert.assertEquals("#FF0000", colorMap.get("red")); assertEquals("#FF0000", colorMap.get("red"));
Assert.assertEquals("#FFFF00", colorMap.get("yellow")); assertEquals("#FFFF00", colorMap.get("yellow"));
Assert.assertEquals("#0000FF", colorMap.get("blue")); assertEquals("#0000FF", colorMap.get("blue"));
} }
@Getter @Getter

View File

@ -2,8 +2,8 @@ package cn.hutool.core.clone;
import lombok.Data; import lombok.Data;
import lombok.EqualsAndHashCode; import lombok.EqualsAndHashCode;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* 克隆单元测试 * 克隆单元测试
@ -18,7 +18,7 @@ public class CloneTest {
//实现Cloneable接口 //实现Cloneable接口
Cat cat = new Cat(); Cat cat = new Cat();
Cat cat2 = cat.clone(); Cat cat2 = cat.clone();
Assert.assertEquals(cat, cat2); assertEquals(cat, cat2);
} }
@Test @Test
@ -26,7 +26,7 @@ public class CloneTest {
//继承CloneSupport类 //继承CloneSupport类
Dog dog = new Dog(); Dog dog = new Dog();
Dog dog2 = dog.clone(); Dog dog2 = dog.clone();
Assert.assertEquals(dog, dog2); assertEquals(dog, dog2);
} }
//------------------------------------------------------------------------------- private Class for test //------------------------------------------------------------------------------- private Class for test

View File

@ -3,13 +3,14 @@ package cn.hutool.core.clone;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.List; import java.util.List;
import java.util.stream.Collectors; import java.util.stream.Collectors;
import java.util.stream.Stream; import java.util.stream.Stream;
import static org.junit.jupiter.api.Assertions.*;
public class DefaultCloneTest { public class DefaultCloneTest {
@Test @Test
@ -19,14 +20,14 @@ public class DefaultCloneTest {
oldCar.setWheelList(Stream.of(new Wheel("h")).collect(Collectors.toList())); oldCar.setWheelList(Stream.of(new Wheel("h")).collect(Collectors.toList()));
Car newCar = oldCar.clone0(); Car newCar = oldCar.clone0();
Assert.assertEquals(oldCar.getId(), newCar.getId()); assertEquals(oldCar.getId(), newCar.getId());
Assert.assertEquals(oldCar.getWheelList(), newCar.getWheelList()); assertEquals(oldCar.getWheelList(), newCar.getWheelList());
newCar.setId(2); newCar.setId(2);
Assert.assertNotEquals(oldCar.getId(), newCar.getId()); assertNotEquals(oldCar.getId(), newCar.getId());
newCar.getWheelList().add(new Wheel("s")); newCar.getWheelList().add(new Wheel("s"));
Assert.assertNotSame(oldCar, newCar); assertNotSame(oldCar, newCar);
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class BCDTest { public class BCDTest {
@ -13,6 +13,6 @@ public class BCDTest {
final byte[] bcd = BCD.strToBcd(strForTest); final byte[] bcd = BCD.strToBcd(strForTest);
final String str = BCD.bcdToStr(bcd); final String str = BCD.bcdToStr(bcd);
//解码BCD //解码BCD
Assert.assertEquals(strForTest, str); assertEquals(strForTest, str);
} }
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.codec;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class Base32Test { public class Base32Test {
@ -11,28 +11,28 @@ public class Base32Test {
public void encodeAndDecodeTest(){ public void encodeAndDecodeTest(){
String a = "伦家是一个非常长的字符串"; String a = "伦家是一个非常长的字符串";
String encode = Base32.encode(a); String encode = Base32.encode(a);
Assert.assertEquals("4S6KNZNOW3TJRL7EXCAOJOFK5GOZ5ZNYXDUZLP7HTKCOLLMX46WKNZFYWI======", encode); assertEquals("4S6KNZNOW3TJRL7EXCAOJOFK5GOZ5ZNYXDUZLP7HTKCOLLMX46WKNZFYWI======", encode);
String decodeStr = Base32.decodeStr(encode); String decodeStr = Base32.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
// 支持小写模式解码 // 支持小写模式解码
decodeStr = Base32.decodeStr(encode.toLowerCase()); decodeStr = Base32.decodeStr(encode.toLowerCase());
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
public void hexEncodeAndDecodeTest(){ public void hexEncodeAndDecodeTest(){
String a = "伦家是一个非常长的字符串"; String a = "伦家是一个非常长的字符串";
String encode = Base32.encodeHex(StrUtil.utf8Bytes(a)); String encode = Base32.encodeHex(StrUtil.utf8Bytes(a));
Assert.assertEquals("SIUADPDEMRJ9HBV4N20E9E5AT6EPTPDON3KPBFV7JA2EBBCNSUMADP5OM8======", encode); assertEquals("SIUADPDEMRJ9HBV4N20E9E5AT6EPTPDON3KPBFV7JA2EBBCNSUMADP5OM8======", encode);
String decodeStr = Base32.decodeStrHex(encode); String decodeStr = Base32.decodeStrHex(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
// 支持小写模式解码 // 支持小写模式解码
decodeStr = Base32.decodeStrHex(encode.toLowerCase()); decodeStr = Base32.decodeStrHex(encode.toLowerCase());
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
@ -40,13 +40,13 @@ public class Base32Test {
String a = RandomUtil.randomString(RandomUtil.randomInt(1000)); String a = RandomUtil.randomString(RandomUtil.randomInt(1000));
String encode = Base32.encode(a); String encode = Base32.encode(a);
String decodeStr = Base32.decodeStr(encode); String decodeStr = Base32.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
public void decodeTest(){ public void decodeTest(){
String a = "伦家是一个非常长的字符串"; String a = "伦家是一个非常长的字符串";
String decodeStr = Base32.decodeStr("4S6KNZNOW3TJRL7EXCAOJOFK5GOZ5ZNYXDUZLP7HTKCOLLMX46WKNZFYWI"); String decodeStr = Base32.decodeStr("4S6KNZNOW3TJRL7EXCAOJOFK5GOZ5ZNYXDUZLP7HTKCOLLMX46WKNZFYWI");
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
} }

View File

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

View File

@ -1,8 +1,8 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Base62单元测试 * Base62单元测试
@ -16,20 +16,20 @@ public class Base62Test {
public void encodeAndDecodeTest() { public void encodeAndDecodeTest() {
String a = "伦家是一个非常长的字符串66"; String a = "伦家是一个非常长的字符串66";
String encode = Base62.encode(a); String encode = Base62.encode(a);
Assert.assertEquals("17vKU8W4JMG8dQF8lk9VNnkdMOeWn4rJMva6F0XsLrrT53iKBnqo", encode); assertEquals("17vKU8W4JMG8dQF8lk9VNnkdMOeWn4rJMva6F0XsLrrT53iKBnqo", encode);
String decodeStr = Base62.decodeStr(encode); String decodeStr = Base62.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
public void encodeAndDecodeInvertedTest() { public void encodeAndDecodeInvertedTest() {
String a = "伦家是一个非常长的字符串66"; String a = "伦家是一个非常长的字符串66";
String encode = Base62.encodeInverted(a); String encode = Base62.encodeInverted(a);
Assert.assertEquals("17Vku8w4jmg8Dqf8LK9vnNKDmoEwN4RjmVA6f0xSlRRt53IkbNQO", encode); assertEquals("17Vku8w4jmg8Dqf8LK9vnNKDmoEwN4RjmVA6f0xSlRRt53IkbNQO", encode);
String decodeStr = Base62.decodeStrInverted(encode); String decodeStr = Base62.decodeStrInverted(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
@ -37,7 +37,7 @@ public class Base62Test {
String a = RandomUtil.randomString(RandomUtil.randomInt(1000)); String a = RandomUtil.randomString(RandomUtil.randomInt(1000));
String encode = Base62.encode(a); String encode = Base62.encode(a);
String decodeStr = Base62.decodeStr(encode); String decodeStr = Base62.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
@ -45,6 +45,6 @@ public class Base62Test {
String a = RandomUtil.randomString(RandomUtil.randomInt(1000)); String a = RandomUtil.randomString(RandomUtil.randomInt(1000));
String encode = Base62.encodeInverted(a); String encode = Base62.encodeInverted(a);
String decodeStr = Base62.decodeStrInverted(encode); String decodeStr = Base62.decodeStrInverted(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
} }

View File

@ -3,8 +3,8 @@ package cn.hutool.core.codec;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Base64单元测试 * Base64单元测试
@ -16,59 +16,59 @@ public class Base64Test {
@Test @Test
public void isBase64Test(){ public void isBase64Test(){
Assert.assertTrue(Base64.isBase64(Base64.encode(RandomUtil.randomString(1000)))); assertTrue(Base64.isBase64(Base64.encode(RandomUtil.randomString(1000))));
} }
@Test @Test
public void isBase64Test2(){ public void isBase64Test2(){
String base64 = "dW1kb3MzejR3bmljM2J6djAyZzcwbWk5M213Nnk3cWQ3eDJwOHFuNXJsYmMwaXhxbmg0dmxrcmN0anRkbmd3\n" + String base64 = "dW1kb3MzejR3bmljM2J6djAyZzcwbWk5M213Nnk3cWQ3eDJwOHFuNXJsYmMwaXhxbmg0dmxrcmN0anRkbmd3\n" +
"ZzcyZWFwanI2NWNneTg2dnp6cmJoMHQ4MHpxY2R6c3pjazZtaQ=="; "ZzcyZWFwanI2NWNneTg2dnp6cmJoMHQ4MHpxY2R6c3pjazZtaQ==";
Assert.assertTrue(Base64.isBase64(base64)); assertTrue(Base64.isBase64(base64));
// '=' 不位于末尾 // '=' 不位于末尾
base64 = "dW1kb3MzejR3bmljM2J6=djAyZzcwbWk5M213Nnk3cWQ3eDJwOHFuNXJsYmMwaXhxbmg0dmxrcmN0anRkbmd3\n" + base64 = "dW1kb3MzejR3bmljM2J6=djAyZzcwbWk5M213Nnk3cWQ3eDJwOHFuNXJsYmMwaXhxbmg0dmxrcmN0anRkbmd3\n" +
"ZzcyZWFwanI2NWNneTg2dnp6cmJoMHQ4MHpxY2R6c3pjazZtaQ="; "ZzcyZWFwanI2NWNneTg2dnp6cmJoMHQ4MHpxY2R6c3pjazZtaQ=";
Assert.assertFalse(Base64.isBase64(base64)); assertFalse(Base64.isBase64(base64));
} }
@Test @Test
public void encodeAndDecodeTest() { public void encodeAndDecodeTest() {
String a = "伦家是一个非常长的字符串66"; String a = "伦家是一个非常长的字符串66";
String encode = Base64.encode(a); String encode = Base64.encode(a);
Assert.assertEquals("5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY=", encode); assertEquals("5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY=", encode);
String decodeStr = Base64.decodeStr(encode); String decodeStr = Base64.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
public void encodeAndDecodeWithoutPaddingTest() { public void encodeAndDecodeWithoutPaddingTest() {
String a = "伦家是一个非常长的字符串66"; String a = "伦家是一个非常长的字符串66";
String encode = Base64.encodeWithoutPadding(StrUtil.utf8Bytes(a)); String encode = Base64.encodeWithoutPadding(StrUtil.utf8Bytes(a));
Assert.assertEquals("5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY", encode); assertEquals("5Lym5a625piv5LiA5Liq6Z2e5bi46ZW/55qE5a2X56ym5LiyNjY", encode);
String decodeStr = Base64.decodeStr(encode); String decodeStr = Base64.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
public void encodeAndDecodeTest2() { public void encodeAndDecodeTest2() {
String a = "a61a5db5a67c01445ca2-HZ20181120172058/pdf/中国电信影像云单体网关Docker版-V1.2.pdf"; String a = "a61a5db5a67c01445ca2-HZ20181120172058/pdf/中国电信影像云单体网关Docker版-V1.2.pdf";
String encode = Base64.encode(a, CharsetUtil.UTF_8); String encode = Base64.encode(a, CharsetUtil.UTF_8);
Assert.assertEquals("YTYxYTVkYjVhNjdjMDE0NDVjYTItSFoyMDE4MTEyMDE3MjA1OC9wZGYv5Lit5Zu955S15L+h5b2x5YOP5LqR5Y2V5L2T572R5YWzRG9ja2Vy54mILVYxLjIucGRm", encode); assertEquals("YTYxYTVkYjVhNjdjMDE0NDVjYTItSFoyMDE4MTEyMDE3MjA1OC9wZGYv5Lit5Zu955S15L+h5b2x5YOP5LqR5Y2V5L2T572R5YWzRG9ja2Vy54mILVYxLjIucGRm", encode);
String decodeStr = Base64.decodeStr(encode, CharsetUtil.UTF_8); String decodeStr = Base64.decodeStr(encode, CharsetUtil.UTF_8);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
public void encodeAndDecodeTest3() { public void encodeAndDecodeTest3() {
String a = ":"; String a = ":";
String encode = Base64.encode(a); String encode = Base64.encode(a);
Assert.assertEquals("Og==", encode); assertEquals("Og==", encode);
String decodeStr = Base64.decodeStr(encode); String decodeStr = Base64.decodeStr(encode);
Assert.assertEquals(a, decodeStr); assertEquals(a, decodeStr);
} }
@Test @Test
@ -77,7 +77,7 @@ public class Base64Test {
String result = Base64.encode(orderDescription, "gbk"); String result = Base64.encode(orderDescription, "gbk");
final String s = Base64.decodeStr(result, "gbk"); final String s = Base64.decodeStr(result, "gbk");
Assert.assertEquals(orderDescription, s); assertEquals(orderDescription, s);
} }
@Test @Test
@ -87,7 +87,7 @@ public class Base64Test {
// Console.log(encode); // Console.log(encode);
final String decodeStr = Base64.decodeStr(encode); final String decodeStr = Base64.decodeStr(encode);
Assert.assertEquals(str, decodeStr); assertEquals(str, decodeStr);
} }
@Test @Test
@ -95,6 +95,6 @@ public class Base64Test {
String a = java.util.Base64.getEncoder().encodeToString("111".getBytes()); //java.util.Base64 String a = java.util.Base64.getEncoder().encodeToString("111".getBytes()); //java.util.Base64
String b = Base64.encode("111"); //cn.hutool.core.codec.Base64 String b = Base64.encode("111"); //cn.hutool.core.codec.Base64
Assert.assertEquals(a, b); assertEquals(a, b);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class CaesarTest { public class CaesarTest {
@ -10,9 +10,9 @@ public class CaesarTest {
String str = "1f2e9df6131b480b9fdddc633cf24996"; String str = "1f2e9df6131b480b9fdddc633cf24996";
String encode = Caesar.encode(str, 3); String encode = Caesar.encode(str, 3);
Assert.assertEquals("1H2G9FH6131D480D9HFFFE633EH24996", encode); assertEquals("1H2G9FH6131D480D9HFFFE633EH24996", encode);
String decode = Caesar.decode(encode, 3); String decode = Caesar.decode(encode, 3);
Assert.assertEquals(str, decode); assertEquals(str, decode);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class HashidsTest { public class HashidsTest {
@Test @Test
@ -11,10 +11,10 @@ public class HashidsTest {
final String encoded2 = hashids.encodeFromHex("0x507f1f77bcf86cd799439011"); final String encoded2 = hashids.encodeFromHex("0x507f1f77bcf86cd799439011");
final String encoded3 = hashids.encodeFromHex("0X507f1f77bcf86cd799439011"); final String encoded3 = hashids.encodeFromHex("0X507f1f77bcf86cd799439011");
Assert.assertEquals("R2qnd2vkOJTXm7XV7yq4", encoded1); assertEquals("R2qnd2vkOJTXm7XV7yq4", encoded1);
Assert.assertEquals(encoded1, encoded2); assertEquals(encoded1, encoded2);
Assert.assertEquals(encoded1, encoded3); assertEquals(encoded1, encoded3);
final String decoded = hashids.decodeToHex(encoded1); final String decoded = hashids.decodeToHex(encoded1);
Assert.assertEquals("507f1f77bcf86cd799439011", decoded); assertEquals("507f1f77bcf86cd799439011", decoded);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class MorseTest { public class MorseTest {
@ -11,23 +11,23 @@ public class MorseTest {
public void test0() { public void test0() {
String text = "Hello World!"; String text = "Hello World!";
String morse = "...././.-../.-../---/-...../.--/---/.-./.-../-../-.-.--/"; String morse = "...././.-../.-../---/-...../.--/---/.-./.-../-../-.-.--/";
Assert.assertEquals(morse, morseCoder.encode(text)); assertEquals(morse, morseCoder.encode(text));
Assert.assertEquals(morseCoder.decode(morse), text.toUpperCase()); assertEquals(morseCoder.decode(morse), text.toUpperCase());
} }
@Test @Test
public void test1() { public void test1() {
String text = "你好,世界!"; String text = "你好,世界!";
String morse = "-..----.--...../-.--..-.-----.-/--------....--../-..---....-.--./---.-.-.-..--../--------.......-/"; String morse = "-..----.--...../-.--..-.-----.-/--------....--../-..---....-.--./---.-.-.-..--../--------.......-/";
Assert.assertEquals(morseCoder.encode(text), morse); assertEquals(morseCoder.encode(text), morse);
Assert.assertEquals(morseCoder.decode(morse), text); assertEquals(morseCoder.decode(morse), text);
} }
@Test @Test
public void test2() { public void test2() {
String text = "こんにちは"; String text = "こんにちは";
String morse = "--.....-.-..--/--....-..-..--/--.....--.-.--/--.....--....-/--.....--.----/"; String morse = "--.....-.-..--/--....-..-..--/--.....--.-.--/--.....--....-/--.....--.----/";
Assert.assertEquals(morseCoder.encode(text), morse); assertEquals(morseCoder.encode(text), morse);
Assert.assertEquals(morseCoder.decode(morse), text); assertEquals(morseCoder.decode(morse), text);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class PunyCodeTest { public class PunyCodeTest {
@ -9,11 +9,11 @@ public class PunyCodeTest {
public void encodeDecodeTest(){ public void encodeDecodeTest(){
final String text = "Hutool编码器"; final String text = "Hutool编码器";
final String strPunyCode = PunyCode.encode(text); final String strPunyCode = PunyCode.encode(text);
Assert.assertEquals("Hutool-ux9js33tgln", strPunyCode); assertEquals("Hutool-ux9js33tgln", strPunyCode);
String decode = PunyCode.decode("Hutool-ux9js33tgln"); String decode = PunyCode.decode("Hutool-ux9js33tgln");
Assert.assertEquals(text, decode); assertEquals(text, decode);
decode = PunyCode.decode("xn--Hutool-ux9js33tgln"); decode = PunyCode.decode("xn--Hutool-ux9js33tgln");
Assert.assertEquals(text, decode); assertEquals(text, decode);
} }
@Test @Test
@ -21,7 +21,7 @@ public class PunyCodeTest {
// 无需编码和解码 // 无需编码和解码
final String text = "Hutool"; final String text = "Hutool";
final String strPunyCode = PunyCode.encode(text); final String strPunyCode = PunyCode.encode(text);
Assert.assertEquals("Hutool", strPunyCode); assertEquals("Hutool", strPunyCode);
} }
@Test @Test
@ -29,24 +29,24 @@ public class PunyCodeTest {
final String domain = "赵新虎.中国"; final String domain = "赵新虎.中国";
final String strPunyCode = PunyCode.encodeDomain(domain); final String strPunyCode = PunyCode.encodeDomain(domain);
final String decode = PunyCode.decodeDomain(strPunyCode); final String decode = PunyCode.decodeDomain(strPunyCode);
Assert.assertEquals(decode, domain); assertEquals(decode, domain);
} }
@Test @Test
public void encodeEncodeDomainTest2(){ public void encodeEncodeDomainTest2(){
final String domain = "赵新虎.com"; final String domain = "赵新虎.com";
final String strPunyCode = PunyCode.encodeDomain(domain); final String strPunyCode = PunyCode.encodeDomain(domain);
Assert.assertEquals("xn--efvz93e52e.com", strPunyCode); assertEquals("xn--efvz93e52e.com", strPunyCode);
final String decode = PunyCode.decodeDomain(strPunyCode); final String decode = PunyCode.decodeDomain(strPunyCode);
Assert.assertEquals(domain, decode); assertEquals(domain, decode);
} }
@Test @Test
public void encodeEncodeDomainTest3(){ public void encodeEncodeDomainTest3(){
final String domain = "赵新虎.COM"; final String domain = "赵新虎.COM";
final String strPunyCode = PunyCode.encodeDomain(domain); final String strPunyCode = PunyCode.encodeDomain(domain);
Assert.assertEquals("xn--efvz93e52e.COM", strPunyCode); assertEquals("xn--efvz93e52e.COM", strPunyCode);
final String decode = PunyCode.decodeDomain(strPunyCode); final String decode = PunyCode.decodeDomain(strPunyCode);
Assert.assertEquals(domain, decode); assertEquals(domain, decode);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.codec; package cn.hutool.core.codec;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class RotTest { public class RotTest {
@ -10,9 +10,9 @@ public class RotTest {
String str = "1f2e9df6131b480b9fdddc633cf24996"; String str = "1f2e9df6131b480b9fdddc633cf24996";
String encode13 = Rot.encode13(str); String encode13 = Rot.encode13(str);
Assert.assertEquals("4s5r2qs9464o713o2sqqqp966ps57229", encode13); assertEquals("4s5r2qs9464o713o2sqqqp966ps57229", encode13);
String decode13 = Rot.decode13(encode13); String decode13 = Rot.decode13(encode13);
Assert.assertEquals(str, decode13); assertEquals(str, decode13);
} }
} }

View File

@ -4,8 +4,8 @@ import cn.hutool.core.map.MapUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.ToString; import lombok.ToString;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.*; import java.util.*;
import java.util.stream.Collector; import java.util.stream.Collector;
@ -19,54 +19,54 @@ public class CollStreamUtilTest {
@Test @Test
public void testToIdentityMap() { public void testToIdentityMap() {
Map<Long, Student> map = CollStreamUtil.toIdentityMap(null, Student::getStudentId); Map<Long, Student> map = CollStreamUtil.toIdentityMap(null, Student::getStudentId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.toIdentityMap(list, Student::getStudentId); map = CollStreamUtil.toIdentityMap(list, Student::getStudentId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 1, 2, "李四")); list.add(new Student(1, 1, 2, "李四"));
list.add(new Student(1, 1, 3, "王五")); list.add(new Student(1, 1, 3, "王五"));
map = CollStreamUtil.toIdentityMap(list, Student::getStudentId); map = CollStreamUtil.toIdentityMap(list, Student::getStudentId);
Assert.assertEquals(map.get(1L).getName(), "张三"); assertEquals(map.get(1L).getName(), "张三");
Assert.assertEquals(map.get(2L).getName(), "李四"); assertEquals(map.get(2L).getName(), "李四");
Assert.assertEquals(map.get(3L).getName(), "王五"); assertEquals(map.get(3L).getName(), "王五");
Assert.assertNull(map.get(4L)); assertNull(map.get(4L));
// 测试value为空时 // 测试value为空时
list.add(null); list.add(null);
map = CollStreamUtil.toIdentityMap(list, Student::getStudentId); map = CollStreamUtil.toIdentityMap(list, Student::getStudentId);
Assert.assertNull(map.get(4L)); assertNull(map.get(4L));
} }
@Test @Test
public void testToMap() { public void testToMap() {
Map<Long, String> map = CollStreamUtil.toMap(null, Student::getStudentId, Student::getName); Map<Long, String> map = CollStreamUtil.toMap(null, Student::getStudentId, Student::getName);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName); map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 1, 2, "李四")); list.add(new Student(1, 1, 2, "李四"));
list.add(new Student(1, 1, 3, "王五")); list.add(new Student(1, 1, 3, "王五"));
map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName); map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName);
Assert.assertEquals(map.get(1L), "张三"); assertEquals(map.get(1L), "张三");
Assert.assertEquals(map.get(2L), "李四"); assertEquals(map.get(2L), "李四");
Assert.assertEquals(map.get(3L), "王五"); assertEquals(map.get(3L), "王五");
Assert.assertNull(map.get(4L)); assertNull(map.get(4L));
// 测试value为空时 // 测试value为空时
list.add(new Student(1, 1, 4, null)); list.add(new Student(1, 1, 4, null));
map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName); map = CollStreamUtil.toMap(list, Student::getStudentId, Student::getName);
Assert.assertNull(map.get(4L)); assertNull(map.get(4L));
} }
@Test @Test
public void testGroupByKey() { public void testGroupByKey() {
Map<Long, List<Student>> map = CollStreamUtil.groupByKey(null, Student::getClassId); Map<Long, List<Student>> map = CollStreamUtil.groupByKey(null, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.groupByKey(list, Student::getClassId); map = CollStreamUtil.groupByKey(list, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 2, 2, "李四")); list.add(new Student(1, 2, 2, "李四"));
list.add(new Student(2, 1, 1, "擎天柱")); list.add(new Student(2, 1, 1, "擎天柱"));
@ -86,16 +86,16 @@ public class CollStreamUtilTest {
List<Student> class3 = new ArrayList<>(); List<Student> class3 = new ArrayList<>();
class3.add(new Student(2, 3, 2, "霸天虎")); class3.add(new Student(2, 3, 2, "霸天虎"));
compare.put(3L, class3); compare.put(3L, class3);
Assert.assertEquals(map, compare); assertEquals(map, compare);
} }
@Test @Test
public void testGroupBy2Key() { public void testGroupBy2Key() {
Map<Long, Map<Long, List<Student>>> map = CollStreamUtil.groupBy2Key(null, Student::getTermId, Student::getClassId); Map<Long, Map<Long, List<Student>>> map = CollStreamUtil.groupBy2Key(null, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.groupBy2Key(list, Student::getTermId, Student::getClassId); map = CollStreamUtil.groupBy2Key(list, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 2, 2, "李四")); list.add(new Student(1, 2, 2, "李四"));
list.add(new Student(1, 2, 3, "王五")); list.add(new Student(1, 2, 3, "王五"));
@ -125,17 +125,17 @@ public class CollStreamUtilTest {
list22.add(new Student(2, 2, 3, "霸天虎")); list22.add(new Student(2, 2, 3, "霸天虎"));
map2.put(2L, list22); map2.put(2L, list22);
compare.put(2L, map2); compare.put(2L, map2);
Assert.assertEquals(map, compare); assertEquals(map, compare);
} }
@Test @Test
public void testGroup2Map() { public void testGroup2Map() {
Map<Long, Map<Long, Student>> map = CollStreamUtil.group2Map(null, Student::getTermId, Student::getClassId); Map<Long, Map<Long, Student>> map = CollStreamUtil.group2Map(null, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.group2Map(list, Student::getTermId, Student::getClassId); map = CollStreamUtil.group2Map(list, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 2, 1, "李四")); list.add(new Student(1, 2, 1, "李四"));
list.add(new Student(2, 2, 1, "王五")); list.add(new Student(2, 2, 1, "王五"));
@ -148,7 +148,7 @@ public class CollStreamUtilTest {
Map<Long, Student> map2 = new HashMap<>(); Map<Long, Student> map2 = new HashMap<>();
map2.put(2L, new Student(2, 2, 1, "王五")); map2.put(2L, new Student(2, 2, 1, "王五"));
compare.put(2L, map2); compare.put(2L, map2);
Assert.assertEquals(compare, map); assertEquals(compare, map);
// 对null友好 // 对null友好
Map<Long, Map<Long, Student>> termIdClassIdStudentMap = CollStreamUtil.group2Map(Arrays.asList(null, new Student(2, 2, 1, "王五")), Student::getTermId, Student::getClassId); Map<Long, Map<Long, Student>> termIdClassIdStudentMap = CollStreamUtil.group2Map(Arrays.asList(null, new Student(2, 2, 1, "王五")), Student::getTermId, Student::getClassId);
@ -156,17 +156,17 @@ public class CollStreamUtilTest {
put(null, MapUtil.of(null, null)); put(null, MapUtil.of(null, null));
put(2L, MapUtil.of(2L, new Student(2, 2, 1, "王五"))); put(2L, MapUtil.of(2L, new Student(2, 2, 1, "王五")));
}}; }};
Assert.assertEquals(termIdClassIdStudentCompareMap, termIdClassIdStudentMap); assertEquals(termIdClassIdStudentCompareMap, termIdClassIdStudentMap);
} }
@Test @Test
public void testGroupKeyValue() { public void testGroupKeyValue() {
Map<Long, List<Long>> map = CollStreamUtil.groupKeyValue(null, Student::getTermId, Student::getClassId); Map<Long, List<Long>> map = CollStreamUtil.groupKeyValue(null, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.groupKeyValue(list, Student::getTermId, Student::getClassId); map = CollStreamUtil.groupKeyValue(list, Student::getTermId, Student::getClassId);
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
list.add(new Student(1, 2, 1, "李四")); list.add(new Student(1, 2, 1, "李四"));
list.add(new Student(2, 2, 1, "王五")); list.add(new Student(2, 2, 1, "王五"));
@ -175,7 +175,7 @@ public class CollStreamUtilTest {
Map<Long, List<Long>> compare = new HashMap<>(); Map<Long, List<Long>> compare = new HashMap<>();
compare.put(1L, Arrays.asList(1L, 2L)); compare.put(1L, Arrays.asList(1L, 2L));
compare.put(2L, Collections.singletonList(2L)); compare.put(2L, Collections.singletonList(2L));
Assert.assertEquals(compare, map); assertEquals(compare, map);
} }
@Test @Test
@ -184,12 +184,12 @@ public class CollStreamUtilTest {
// 参数null测试 // 参数null测试
Map<Long, List<Student>> map = CollStreamUtil.groupBy(null, Student::getTermId, Collectors.toList()); Map<Long, List<Student>> map = CollStreamUtil.groupBy(null, Student::getTermId, Collectors.toList());
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
// 参数空数组测试 // 参数空数组测试
List<Student> list = new ArrayList<>(); List<Student> list = new ArrayList<>();
map = CollStreamUtil.groupBy(list, Student::getTermId, Collectors.toList()); map = CollStreamUtil.groupBy(list, Student::getTermId, Collectors.toList());
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
// 放入元素 // 放入元素
list.add(new Student(1, 1, 1, "张三")); list.add(new Student(1, 1, 1, "张三"));
@ -198,11 +198,11 @@ public class CollStreamUtilTest {
// 先根据termId分组再通过classId比较找出最大值所属的那个Student,返回的Optional // 先根据termId分组再通过classId比较找出最大值所属的那个Student,返回的Optional
Map<Long, Optional<Student>> longOptionalMap = CollStreamUtil.groupBy(list, Student::getTermId, Collectors.maxBy(Comparator.comparing(Student::getClassId))); Map<Long, Optional<Student>> longOptionalMap = CollStreamUtil.groupBy(list, Student::getTermId, Collectors.maxBy(Comparator.comparing(Student::getClassId)));
//noinspection OptionalGetWithoutIsPresent //noinspection OptionalGetWithoutIsPresent
Assert.assertEquals("李四", longOptionalMap.get(1L).get().getName()); assertEquals("李四", longOptionalMap.get(1L).get().getName());
// 先根据termId分组再转换为Map<studentId,name> // 先根据termId分组再转换为Map<studentId,name>
Map<Long, HashMap<Long, String>> groupThen = CollStreamUtil.groupBy(list, Student::getTermId, Collector.of(HashMap::new, (m, v) -> m.put(v.getStudentId(), v.getName()), (l, r) -> l)); Map<Long, HashMap<Long, String>> groupThen = CollStreamUtil.groupBy(list, Student::getTermId, Collector.of(HashMap::new, (m, v) -> m.put(v.getStudentId(), v.getName()), (l, r) -> l));
Assert.assertEquals( assertEquals(
MapUtil.builder() MapUtil.builder()
.put(1L, MapUtil.builder().put(1L, "李四").build()) .put(1L, MapUtil.builder().put(1L, "李四").build())
.put(2L, MapUtil.builder().put(1L, "王五").build()) .put(2L, MapUtil.builder().put(1L, "王五").build())
@ -217,23 +217,23 @@ public class CollStreamUtilTest {
Map<Long, List<Student>> termIdStudentsCompareMap = new HashMap<>(); Map<Long, List<Student>> termIdStudentsCompareMap = new HashMap<>();
termIdStudentsCompareMap.put(null, Arrays.asList(null, null)); termIdStudentsCompareMap.put(null, Arrays.asList(null, null));
termIdStudentsCompareMap.put(1L, Arrays.asList(new Student(1L, 1, 1, "张三"), new Student(1L, 2, 1, "李四"))); termIdStudentsCompareMap.put(1L, Arrays.asList(new Student(1L, 1, 1, "张三"), new Student(1L, 2, 1, "李四")));
Assert.assertEquals(termIdStudentsCompareMap, termIdStudentsMap); assertEquals(termIdStudentsCompareMap, termIdStudentsMap);
Map<Long, Long> termIdCountMap = CollStreamUtil.groupBy(students, Student::getTermId, Collectors.counting()); Map<Long, Long> termIdCountMap = CollStreamUtil.groupBy(students, Student::getTermId, Collectors.counting());
Map<Long, Long> termIdCountCompareMap = new HashMap<>(); Map<Long, Long> termIdCountCompareMap = new HashMap<>();
termIdCountCompareMap.put(null, 2L); termIdCountCompareMap.put(null, 2L);
termIdCountCompareMap.put(1L, 2L); termIdCountCompareMap.put(1L, 2L);
Assert.assertEquals(termIdCountCompareMap, termIdCountMap); assertEquals(termIdCountCompareMap, termIdCountMap);
} }
@Test @Test
public void testTranslate2List() { public void testTranslate2List() {
List<String> list = CollStreamUtil.toList(null, Student::getName); List<String> list = CollStreamUtil.toList(null, Student::getName);
Assert.assertEquals(list, Collections.EMPTY_LIST); assertEquals(list, Collections.EMPTY_LIST);
List<Student> students = new ArrayList<>(); List<Student> students = new ArrayList<>();
list = CollStreamUtil.toList(students, Student::getName); list = CollStreamUtil.toList(students, Student::getName);
Assert.assertEquals(list, Collections.EMPTY_LIST); assertEquals(list, Collections.EMPTY_LIST);
students.add(new Student(1, 1, 1, "张三")); students.add(new Student(1, 1, 1, "张三"));
students.add(new Student(1, 2, 2, "李四")); students.add(new Student(1, 2, 2, "李四"));
students.add(new Student(2, 1, 1, "李四")); students.add(new Student(2, 1, 1, "李四"));
@ -246,16 +246,16 @@ public class CollStreamUtilTest {
compare.add("李四"); compare.add("李四");
compare.add("李四"); compare.add("李四");
compare.add("霸天虎"); compare.add("霸天虎");
Assert.assertEquals(list, compare); assertEquals(list, compare);
} }
@Test @Test
public void testTranslate2Set() { public void testTranslate2Set() {
Set<String> set = CollStreamUtil.toSet(null, Student::getName); Set<String> set = CollStreamUtil.toSet(null, Student::getName);
Assert.assertEquals(set, Collections.EMPTY_SET); assertEquals(set, Collections.EMPTY_SET);
List<Student> students = new ArrayList<>(); List<Student> students = new ArrayList<>();
set = CollStreamUtil.toSet(students, Student::getName); set = CollStreamUtil.toSet(students, Student::getName);
Assert.assertEquals(set, Collections.EMPTY_SET); assertEquals(set, Collections.EMPTY_SET);
students.add(new Student(1, 1, 1, "张三")); students.add(new Student(1, 1, 1, "张三"));
students.add(new Student(1, 2, 2, "李四")); students.add(new Student(1, 2, 2, "李四"));
students.add(new Student(2, 1, 1, "李四")); students.add(new Student(2, 1, 1, "李四"));
@ -266,7 +266,7 @@ public class CollStreamUtilTest {
compare.add("张三"); compare.add("张三");
compare.add("李四"); compare.add("李四");
compare.add("霸天虎"); compare.add("霸天虎");
Assert.assertEquals(set, compare); assertEquals(set, compare);
} }
@Test @Test
@ -274,19 +274,19 @@ public class CollStreamUtilTest {
Map<Long, Student> map1 = null; Map<Long, Student> map1 = null;
Map<Long, Student> map2 = Collections.emptyMap(); Map<Long, Student> map2 = Collections.emptyMap();
Map<Long, String> map = CollStreamUtil.merge(map1, map2, (s1, s2) -> s1.getName() + s2.getName()); Map<Long, String> map = CollStreamUtil.merge(map1, map2, (s1, s2) -> s1.getName() + s2.getName());
Assert.assertEquals(map, Collections.EMPTY_MAP); assertEquals(map, Collections.EMPTY_MAP);
map1 = new HashMap<>(); map1 = new HashMap<>();
map1.put(1L, new Student(1, 1, 1, "张三")); map1.put(1L, new Student(1, 1, 1, "张三"));
map = CollStreamUtil.merge(map1, map2, this::merge); map = CollStreamUtil.merge(map1, map2, this::merge);
Map<Long, String> temp = new HashMap<>(); Map<Long, String> temp = new HashMap<>();
temp.put(1L, "张三"); temp.put(1L, "张三");
Assert.assertEquals(map, temp); assertEquals(map, temp);
map2 = new HashMap<>(); map2 = new HashMap<>();
map2.put(1L, new Student(2, 1, 1, "李四")); map2.put(1L, new Student(2, 1, 1, "李四"));
map = CollStreamUtil.merge(map1, map2, this::merge); map = CollStreamUtil.merge(map1, map2, this::merge);
Map<Long, String> compare = new HashMap<>(); Map<Long, String> compare = new HashMap<>();
compare.put(1L, "张三李四"); compare.put(1L, "张三李四");
Assert.assertEquals(map, compare); assertEquals(map, compare);
} }
private String merge(Student student1, Student student2) { private String merge(Student student1, Student student2) {

View File

@ -5,16 +5,13 @@ import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Dict; import cn.hutool.core.lang.Dict;
import cn.hutool.core.map.MapUtil; import cn.hutool.core.map.MapUtil;
import cn.hutool.core.util.StrUtil; import cn.hutool.core.util.StrUtil;
import lombok.AllArgsConstructor; import lombok.*;
import lombok.Data; import org.junit.jupiter.api.Test;
import lombok.EqualsAndHashCode;
import lombok.NoArgsConstructor;
import lombok.ToString;
import org.junit.Assert;
import org.junit.Test;
import java.util.*; import java.util.*;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* 集合工具类单元测试 * 集合工具类单元测试
* *
@ -25,8 +22,8 @@ public class CollUtilTest {
@Test @Test
public void testPredicateContains() { public void testPredicateContains() {
final ArrayList<String> list = CollUtil.newArrayList("bbbbb", "aaaaa", "ccccc"); final ArrayList<String> list = CollUtil.newArrayList("bbbbb", "aaaaa", "ccccc");
Assert.assertTrue(CollUtil.contains(list, s -> s.startsWith("a"))); assertTrue(CollUtil.contains(list, s -> s.startsWith("a")));
Assert.assertFalse(CollUtil.contains(list, s -> s.startsWith("d"))); assertFalse(CollUtil.contains(list, s -> s.startsWith("d")));
} }
@Test @Test
@ -36,14 +33,14 @@ public class CollUtilTest {
final ArrayList<Integer> exceptResultList = CollUtil.newArrayList(1); final ArrayList<Integer> exceptResultList = CollUtil.newArrayList(1);
List<Integer> resultList = CollUtil.removeWithAddIf(list, ele -> 1 == ele); List<Integer> resultList = CollUtil.removeWithAddIf(list, ele -> 1 == ele);
Assert.assertEquals(list, exceptRemovedList); assertEquals(list, exceptRemovedList);
Assert.assertEquals(resultList, exceptResultList); assertEquals(resultList, exceptResultList);
list = CollUtil.newArrayList(1, 2, 3); list = CollUtil.newArrayList(1, 2, 3);
resultList = new ArrayList<>(); resultList = new ArrayList<>();
CollUtil.removeWithAddIf(list, resultList, ele -> 1 == ele); CollUtil.removeWithAddIf(list, resultList, ele -> 1 == ele);
Assert.assertEquals(list, exceptRemovedList); assertEquals(list, exceptRemovedList);
Assert.assertEquals(resultList, exceptResultList); assertEquals(resultList, exceptResultList);
} }
@Test @Test
@ -52,17 +49,17 @@ public class CollUtilTest {
List<String> answerList = CollUtil.newArrayList("a", "b"); List<String> answerList = CollUtil.newArrayList("a", "b");
CollUtil.padLeft(srcList, 1, "b"); CollUtil.padLeft(srcList, 1, "b");
CollUtil.padLeft(srcList, 2, "a"); CollUtil.padLeft(srcList, 2, "a");
Assert.assertEquals(srcList, answerList); assertEquals(srcList, answerList);
srcList = CollUtil.newArrayList("a", "b"); srcList = CollUtil.newArrayList("a", "b");
answerList = CollUtil.newArrayList("a", "b"); answerList = CollUtil.newArrayList("a", "b");
CollUtil.padLeft(srcList, 2, "a"); CollUtil.padLeft(srcList, 2, "a");
Assert.assertEquals(srcList, answerList); assertEquals(srcList, answerList);
srcList = CollUtil.newArrayList("c"); srcList = CollUtil.newArrayList("c");
answerList = CollUtil.newArrayList("a", "a", "c"); answerList = CollUtil.newArrayList("a", "a", "c");
CollUtil.padLeft(srcList, 3, "a"); CollUtil.padLeft(srcList, 3, "a");
Assert.assertEquals(srcList, answerList); assertEquals(srcList, answerList);
} }
@Test @Test
@ -70,18 +67,19 @@ public class CollUtilTest {
final List<String> srcList = CollUtil.newArrayList("a"); final List<String> srcList = CollUtil.newArrayList("a");
final List<String> answerList = CollUtil.newArrayList("a", "b", "b", "b", "b"); final List<String> answerList = CollUtil.newArrayList("a", "b", "b", "b", "b");
CollUtil.padRight(srcList, 5, "b"); CollUtil.padRight(srcList, 5, "b");
Assert.assertEquals(srcList, answerList); assertEquals(srcList, answerList);
} }
@SuppressWarnings("ConstantValue")
@Test @Test
public void isNotEmptyTest() { public void isNotEmptyTest() {
Assert.assertFalse(CollUtil.isNotEmpty((Collection<?>) null)); assertFalse(CollUtil.isNotEmpty((Collection<?>) null));
} }
@Test @Test
public void newHashSetTest() { public void newHashSetTest() {
final Set<String> set = CollUtil.newHashSet((String[]) null); final Set<String> set = CollUtil.newHashSet((String[]) null);
Assert.assertNotNull(set); assertNotNull(set);
} }
@Test @Test
@ -91,14 +89,14 @@ public class CollUtilTest {
final String[] keys = v1.keySet().toArray(new String[0]); final String[] keys = v1.keySet().toArray(new String[0]);
final ArrayList<Object> v1s = CollUtil.valuesOfKeys(v1, keys); final ArrayList<Object> v1s = CollUtil.valuesOfKeys(v1, keys);
Assert.assertTrue(v1s.contains(12)); assertTrue(v1s.contains(12));
Assert.assertTrue(v1s.contains(23)); assertTrue(v1s.contains(23));
Assert.assertTrue(v1s.contains("张三")); assertTrue(v1s.contains("张三"));
final ArrayList<Object> v2s = CollUtil.valuesOfKeys(v2, keys); final ArrayList<Object> v2s = CollUtil.valuesOfKeys(v2, keys);
Assert.assertTrue(v2s.contains(15)); assertTrue(v2s.contains(15));
Assert.assertTrue(v2s.contains(13)); assertTrue(v2s.contains(13));
Assert.assertTrue(v2s.contains("李四")); assertTrue(v2s.contains("李四"));
} }
@Test @Test
@ -108,7 +106,7 @@ public class CollUtilTest {
final Collection<String> union = CollUtil.union(list1, list2); final Collection<String> union = CollUtil.union(list1, list2);
Assert.assertEquals(3, CollUtil.count(union, "b"::equals)); assertEquals(3, CollUtil.count(union, "b"::equals));
} }
@Test @Test
@ -117,7 +115,7 @@ public class CollUtilTest {
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d"); final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d");
final Collection<String> intersection = CollUtil.intersection(list1, list2); final Collection<String> intersection = CollUtil.intersection(list1, list2);
Assert.assertEquals(2, CollUtil.count(intersection, "b"::equals)); assertEquals(2, CollUtil.count(intersection, "b"::equals));
} }
@Test @Test
@ -127,10 +125,10 @@ public class CollUtilTest {
final ArrayList<String> list3 = CollUtil.newArrayList(); final ArrayList<String> list3 = CollUtil.newArrayList();
final Collection<String> intersectionDistinct = CollUtil.intersectionDistinct(list1, list2); final Collection<String> intersectionDistinct = CollUtil.intersectionDistinct(list1, list2);
Assert.assertEquals(CollUtil.newLinkedHashSet("a", "b", "c", "d"), intersectionDistinct); assertEquals(CollUtil.newLinkedHashSet("a", "b", "c", "d"), intersectionDistinct);
final Collection<String> intersectionDistinct2 = CollUtil.intersectionDistinct(list1, list2, list3); final Collection<String> intersectionDistinct2 = CollUtil.intersectionDistinct(list1, list2, list3);
Assert.assertTrue(intersectionDistinct2.isEmpty()); assertTrue(intersectionDistinct2.isEmpty());
} }
@Test @Test
@ -139,14 +137,14 @@ public class CollUtilTest {
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2"); final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> disjunction = CollUtil.disjunction(list1, list2); final Collection<String> disjunction = CollUtil.disjunction(list1, list2);
Assert.assertTrue(disjunction.contains("b")); assertTrue(disjunction.contains("b"));
Assert.assertTrue(disjunction.contains("x2")); assertTrue(disjunction.contains("x2"));
Assert.assertTrue(disjunction.contains("x")); assertTrue(disjunction.contains("x"));
final Collection<String> disjunction2 = CollUtil.disjunction(list2, list1); final Collection<String> disjunction2 = CollUtil.disjunction(list2, list1);
Assert.assertTrue(disjunction2.contains("b")); assertTrue(disjunction2.contains("b"));
Assert.assertTrue(disjunction2.contains("x2")); assertTrue(disjunction2.contains("x2"));
Assert.assertTrue(disjunction2.contains("x")); assertTrue(disjunction2.contains("x"));
} }
@Test @Test
@ -156,9 +154,9 @@ public class CollUtilTest {
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2"); final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> disjunction = CollUtil.disjunction(list1, list2); final Collection<String> disjunction = CollUtil.disjunction(list1, list2);
Assert.assertEquals(list2, disjunction); assertEquals(list2, disjunction);
final Collection<String> disjunction2 = CollUtil.disjunction(list2, list1); final Collection<String> disjunction2 = CollUtil.disjunction(list2, list1);
Assert.assertEquals(list2, disjunction2); assertEquals(list2, disjunction2);
} }
@Test @Test
@ -168,19 +166,19 @@ public class CollUtilTest {
final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "c"); final ArrayList<String> list2 = CollUtil.newArrayList("a", "b", "c");
final Collection<String> disjunction = CollUtil.disjunction(list1, list2); final Collection<String> disjunction = CollUtil.disjunction(list1, list2);
Assert.assertTrue(disjunction.contains("1")); assertTrue(disjunction.contains("1"));
Assert.assertTrue(disjunction.contains("2")); assertTrue(disjunction.contains("2"));
Assert.assertTrue(disjunction.contains("3")); assertTrue(disjunction.contains("3"));
Assert.assertTrue(disjunction.contains("a")); assertTrue(disjunction.contains("a"));
Assert.assertTrue(disjunction.contains("b")); assertTrue(disjunction.contains("b"));
Assert.assertTrue(disjunction.contains("c")); assertTrue(disjunction.contains("c"));
final Collection<String> disjunction2 = CollUtil.disjunction(list2, list1); final Collection<String> disjunction2 = CollUtil.disjunction(list2, list1);
Assert.assertTrue(disjunction2.contains("1")); assertTrue(disjunction2.contains("1"));
Assert.assertTrue(disjunction2.contains("2")); assertTrue(disjunction2.contains("2"));
Assert.assertTrue(disjunction2.contains("3")); assertTrue(disjunction2.contains("3"));
Assert.assertTrue(disjunction2.contains("a")); assertTrue(disjunction2.contains("a"));
Assert.assertTrue(disjunction2.contains("b")); assertTrue(disjunction2.contains("b"));
Assert.assertTrue(disjunction2.contains("c")); assertTrue(disjunction2.contains("c"));
} }
@Test @Test
@ -188,8 +186,8 @@ public class CollUtilTest {
final List<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x"); final List<String> list1 = CollUtil.newArrayList("a", "b", "b", "c", "d", "x");
final List<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2"); final List<String> list2 = CollUtil.newArrayList("a", "b", "b", "b", "c", "d", "x2");
final Collection<String> subtract = CollUtil.subtract(list1, list2); final Collection<String> subtract = CollUtil.subtract(list1, list2);
Assert.assertEquals(1, subtract.size()); assertEquals(1, subtract.size());
Assert.assertEquals("x", subtract.iterator().next()); assertEquals("x", subtract.iterator().next());
} }
@Test @Test
@ -200,7 +198,7 @@ public class CollUtilTest {
map1.put("2", "v2"); map1.put("2", "v2");
map2.put("2", "v2"); map2.put("2", "v2");
final Collection<String> r2 = CollUtil.subtract(map1.keySet(), map2.keySet()); final Collection<String> r2 = CollUtil.subtract(map1.keySet(), map2.keySet());
Assert.assertEquals("[1]", r2.toString()); assertEquals("[1]", r2.toString());
} }
@Test @Test
@ -211,7 +209,7 @@ public class CollUtilTest {
map1.put("2", "v2"); map1.put("2", "v2");
map2.put("2", "v2"); map2.put("2", "v2");
final List<String> r2 = CollUtil.subtractToList(map1.keySet(), map2.keySet()); final List<String> r2 = CollUtil.subtractToList(map1.keySet(), map2.keySet());
Assert.assertEquals("[1]", r2.toString()); assertEquals("[1]", r2.toString());
} }
@Test @Test
@ -227,13 +225,13 @@ public class CollUtilTest {
// ---------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------
final ArrayList<HashMap<String, String>> list = CollUtil.newArrayList(map1, map2); final ArrayList<HashMap<String, String>> list = CollUtil.newArrayList(map1, map2);
final Map<String, List<String>> map = CollUtil.toListMap(list); final Map<String, List<String>> map = CollUtil.toListMap(list);
Assert.assertEquals("值1", map.get("a").get(0)); assertEquals("值1", map.get("a").get(0));
Assert.assertEquals("值2", map.get("a").get(1)); assertEquals("值2", map.get("a").get(1));
// ---------------------------------------------------------------------------------------- // ----------------------------------------------------------------------------------------
final List<Map<String, String>> listMap = CollUtil.toMapList(map); final List<Map<String, String>> listMap = CollUtil.toMapList(map);
Assert.assertEquals("值1", listMap.get(0).get("a")); assertEquals("值1", listMap.get(0).get("a"));
Assert.assertEquals("值2", listMap.get(1).get("a")); assertEquals("值2", listMap.get(1).get("a"));
} }
@Test @Test
@ -243,24 +241,24 @@ public class CollUtilTest {
final ArrayList<Dict> list = CollUtil.newArrayList(v1, v2); final ArrayList<Dict> list = CollUtil.newArrayList(v1, v2);
final List<Object> fieldValues = CollUtil.getFieldValues(list, "name"); final List<Object> fieldValues = CollUtil.getFieldValues(list, "name");
Assert.assertEquals("张三", fieldValues.get(0)); assertEquals("张三", fieldValues.get(0));
Assert.assertEquals("李四", fieldValues.get(1)); assertEquals("李四", fieldValues.get(1));
} }
@Test @Test
public void splitTest() { public void splitTest() {
final ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9); final ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
final List<List<Integer>> split = CollUtil.split(list, 3); final List<List<Integer>> split = CollUtil.split(list, 3);
Assert.assertEquals(3, split.size()); assertEquals(3, split.size());
Assert.assertEquals(3, split.get(0).size()); assertEquals(3, split.get(0).size());
} }
@Test @Test
public void splitTest2() { public void splitTest2() {
final ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9); final ArrayList<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
final List<List<Integer>> split = CollUtil.split(list, Integer.MAX_VALUE); final List<List<Integer>> split = CollUtil.split(list, Integer.MAX_VALUE);
Assert.assertEquals(1, split.size()); assertEquals(1, split.size());
Assert.assertEquals(9, split.get(0).size()); assertEquals(9, split.get(0).size());
} }
@Test @Test
@ -277,7 +275,7 @@ public class CollUtilTest {
result[0] = value; result[0] = value;
} }
}); });
Assert.assertEquals("1", result[0]); assertEquals("1", result[0]);
} }
@Test @Test
@ -286,7 +284,7 @@ public class CollUtilTest {
final Collection<String> filtered = CollUtil.edit(list, t -> t + 1); final Collection<String> filtered = CollUtil.edit(list, t -> t + 1);
Assert.assertEquals(CollUtil.newArrayList("a1", "b1", "c1"), filtered); assertEquals(CollUtil.newArrayList("a1", "b1", "c1"), filtered);
} }
@Test @Test
@ -296,8 +294,8 @@ public class CollUtilTest {
final ArrayList<String> filtered = CollUtil.filter(list, t -> false == "a".equals(t)); final ArrayList<String> filtered = CollUtil.filter(list, t -> false == "a".equals(t));
// 原地过滤 // 原地过滤
Assert.assertSame(list, filtered); assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("b", "c"), filtered); assertEquals(CollUtil.newArrayList("b", "c"), filtered);
} }
@Test @Test
@ -305,7 +303,7 @@ public class CollUtilTest {
final Set<String> set = CollUtil.newLinkedHashSet("a", "b", "", " ", "c"); final Set<String> set = CollUtil.newLinkedHashSet("a", "b", "", " ", "c");
final Set<String> filtered = CollUtil.filter(set, StrUtil::isNotBlank); final Set<String> filtered = CollUtil.filter(set, StrUtil::isNotBlank);
Assert.assertEquals(CollUtil.newLinkedHashSet("a", "b", "c"), filtered); assertEquals(CollUtil.newLinkedHashSet("a", "b", "c"), filtered);
} }
@Test @Test
@ -321,12 +319,12 @@ public class CollUtilTest {
return true; return true;
}); });
Assert.assertEquals(1, removed.size()); assertEquals(1, removed.size());
Assert.assertEquals("a", removed.get(0)); assertEquals("a", removed.get(0));
// 原地过滤 // 原地过滤
Assert.assertSame(list, filtered); assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("b", "c"), filtered); assertEquals(CollUtil.newArrayList("b", "c"), filtered);
} }
@Test @Test
@ -336,8 +334,8 @@ public class CollUtilTest {
final ArrayList<String> filtered = CollUtil.removeNull(list); final ArrayList<String> filtered = CollUtil.removeNull(list);
// 原地过滤 // 原地过滤
Assert.assertSame(list, filtered); assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("a", "b", "c", "", " "), filtered); assertEquals(CollUtil.newArrayList("a", "b", "c", "", " "), filtered);
} }
@Test @Test
@ -347,8 +345,8 @@ public class CollUtilTest {
final ArrayList<String> filtered = CollUtil.removeEmpty(list); final ArrayList<String> filtered = CollUtil.removeEmpty(list);
// 原地过滤 // 原地过滤
Assert.assertSame(list, filtered); assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("a", "b", "c", " "), filtered); assertEquals(CollUtil.newArrayList("a", "b", "c", " "), filtered);
} }
@Test @Test
@ -358,32 +356,32 @@ public class CollUtilTest {
final ArrayList<String> filtered = CollUtil.removeBlank(list); final ArrayList<String> filtered = CollUtil.removeBlank(list);
// 原地过滤 // 原地过滤
Assert.assertSame(list, filtered); assertSame(list, filtered);
Assert.assertEquals(CollUtil.newArrayList("a", "b", "c"), filtered); assertEquals(CollUtil.newArrayList("a", "b", "c"), filtered);
} }
@Test @Test
public void groupTest() { public void groupTest() {
final List<String> list = CollUtil.newArrayList("1", "2", "3", "4", "5", "6"); final List<String> list = CollUtil.newArrayList("1", "2", "3", "4", "5", "6");
final List<List<String>> group = CollUtil.group(list, null); final List<List<String>> group = CollUtil.group(list, null);
Assert.assertTrue(group.size() > 0); assertFalse(group.isEmpty());
final List<List<String>> group2 = CollUtil.group(list, t -> { final List<List<String>> group2 = CollUtil.group(list, t -> {
// 按照奇数偶数分类 // 按照奇数偶数分类
return Integer.parseInt(t) % 2; return Integer.parseInt(t) % 2;
}); });
Assert.assertEquals(CollUtil.newArrayList("2", "4", "6"), group2.get(0)); assertEquals(CollUtil.newArrayList("2", "4", "6"), group2.get(0));
Assert.assertEquals(CollUtil.newArrayList("1", "3", "5"), group2.get(1)); assertEquals(CollUtil.newArrayList("1", "3", "5"), group2.get(1));
} }
@Test @Test
public void groupByFieldTest() { public void groupByFieldTest() {
final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12)); final List<TestBean> list = CollUtil.newArrayList(new TestBean("张三", 12), new TestBean("李四", 13), new TestBean("王五", 12));
final List<List<TestBean>> groupByField = CollUtil.groupByField(list, "age"); final List<List<TestBean>> groupByField = CollUtil.groupByField(list, "age");
Assert.assertEquals("张三", groupByField.get(0).get(0).getName()); assertEquals("张三", groupByField.get(0).get(0).getName());
Assert.assertEquals("王五", groupByField.get(0).get(1).getName()); assertEquals("王五", groupByField.get(0).get(1).getName());
Assert.assertEquals("李四", groupByField.get(1).get(0).getName()); assertEquals("李四", groupByField.get(1).get(0).getName());
} }
@Test @Test
@ -395,9 +393,9 @@ public class CollUtilTest {
); );
CollUtil.sortByProperty(list, "createTime"); CollUtil.sortByProperty(list, "createTime");
Assert.assertEquals("李四", list.get(0).getName()); assertEquals("李四", list.get(0).getName());
Assert.assertEquals("王五", list.get(1).getName()); assertEquals("王五", list.get(1).getName());
Assert.assertEquals("张三", list.get(2).getName()); assertEquals("张三", list.get(2).getName());
} }
@Test @Test
@ -409,9 +407,9 @@ public class CollUtilTest {
); );
CollUtil.sortByProperty(list, "age"); CollUtil.sortByProperty(list, "age");
Assert.assertEquals("李四", list.get(0).getName()); assertEquals("李四", list.get(0).getName());
Assert.assertEquals("张三", list.get(1).getName()); assertEquals("张三", list.get(1).getName());
Assert.assertEquals("王五", list.get(2).getName()); assertEquals("王五", list.get(2).getName());
} }
@Test @Test
@ -422,9 +420,9 @@ public class CollUtilTest {
); );
final Map<String, TestBean> map = CollUtil.fieldValueMap(list, "name"); final Map<String, TestBean> map = CollUtil.fieldValueMap(list, "name");
Assert.assertEquals("李四", map.get("李四").getName()); assertEquals("李四", map.get("李四").getName());
Assert.assertEquals("王五", map.get("王五").getName()); assertEquals("王五", map.get("王五").getName());
Assert.assertEquals("张三", map.get("张三").getName()); assertEquals("张三", map.get("张三").getName());
} }
@Test @Test
@ -435,21 +433,21 @@ public class CollUtilTest {
); );
final Map<String, Integer> map = CollUtil.fieldValueAsMap(list, "name", "age"); final Map<String, Integer> map = CollUtil.fieldValueAsMap(list, "name", "age");
Assert.assertEquals(new Integer(12), map.get("张三")); assertEquals(new Integer(12), map.get("张三"));
Assert.assertEquals(new Integer(13), map.get("李四")); assertEquals(new Integer(13), map.get("李四"));
Assert.assertEquals(new Integer(14), map.get("王五")); assertEquals(new Integer(14), map.get("王五"));
} }
@Test @Test
public void emptyTest() { public void emptyTest() {
final SortedSet<String> emptySortedSet = CollUtil.empty(SortedSet.class); final SortedSet<String> emptySortedSet = CollUtil.empty(SortedSet.class);
Assert.assertEquals(Collections.emptySortedSet(), emptySortedSet); assertEquals(Collections.emptySortedSet(), emptySortedSet);
final Set<String> emptySet = CollUtil.empty(Set.class); final Set<String> emptySet = CollUtil.empty(Set.class);
Assert.assertEquals(Collections.emptySet(), emptySet); assertEquals(Collections.emptySet(), emptySet);
final List<String> emptyList = CollUtil.empty(List.class); final List<String> emptyList = CollUtil.empty(List.class);
Assert.assertEquals(Collections.emptyList(), emptyList); assertEquals(Collections.emptyList(), emptyList);
} }
@Data @Data
@ -470,16 +468,16 @@ public class CollUtilTest {
final List<Object> list1 = CollUtil.list(false); final List<Object> list1 = CollUtil.list(false);
final List<Object> list2 = CollUtil.list(true); final List<Object> list2 = CollUtil.list(true);
Assert.assertTrue(list1 instanceof ArrayList); assertInstanceOf(ArrayList.class, list1);
Assert.assertTrue(list2 instanceof LinkedList); assertInstanceOf(LinkedList.class, list2);
} }
@Test @Test
public void listTest2() { public void listTest2() {
final List<String> list1 = CollUtil.list(false, "a", "b", "c"); final List<String> list1 = CollUtil.list(false, "a", "b", "c");
final List<String> list2 = CollUtil.list(true, "a", "b", "c"); final List<String> list2 = CollUtil.list(true, "a", "b", "c");
Assert.assertEquals("[a, b, c]", list1.toString()); assertEquals("[a, b, c]", list1.toString());
Assert.assertEquals("[a, b, c]", list2.toString()); assertEquals("[a, b, c]", list2.toString());
} }
@Test @Test
@ -491,18 +489,18 @@ public class CollUtilTest {
final List<String> list1 = CollUtil.list(false, set); final List<String> list1 = CollUtil.list(false, set);
final List<String> list2 = CollUtil.list(true, set); final List<String> list2 = CollUtil.list(true, set);
Assert.assertEquals("[a, b, c]", list1.toString()); assertEquals("[a, b, c]", list1.toString());
Assert.assertEquals("[a, b, c]", list2.toString()); assertEquals("[a, b, c]", list2.toString());
} }
@Test @Test
public void getTest() { public void getTest() {
final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D"); final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D");
String str = CollUtil.get(set, 2); String str = CollUtil.get(set, 2);
Assert.assertEquals("C", str); assertEquals("C", str);
str = CollUtil.get(set, -1); str = CollUtil.get(set, -1);
Assert.assertEquals("D", str); assertEquals("D", str);
} }
@Test @Test
@ -515,10 +513,10 @@ public class CollUtilTest {
list2.add("3"); list2.add("3");
CollUtil.addAllIfNotContains(list1, list2); CollUtil.addAllIfNotContains(list1, list2);
Assert.assertEquals(3, list1.size()); assertEquals(3, list1.size());
Assert.assertEquals("1", list1.get(0)); assertEquals("1", list1.get(0));
Assert.assertEquals("2", list1.get(1)); assertEquals("2", list1.get(1));
Assert.assertEquals("3", list1.get(2)); assertEquals("3", list1.get(2));
} }
@Test @Test
@ -534,7 +532,7 @@ public class CollUtilTest {
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
arrayList.add(null); arrayList.add(null);
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -551,7 +549,7 @@ public class CollUtilTest {
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
arrayList.add(null); arrayList.add(null);
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -566,7 +564,7 @@ public class CollUtilTest {
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -579,7 +577,7 @@ public class CollUtilTest {
// Act // Act
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
Assert.assertTrue(retval.isEmpty()); assertTrue(retval.isEmpty());
} }
@Test @Test
@ -594,7 +592,7 @@ public class CollUtilTest {
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -609,21 +607,23 @@ public class CollUtilTest {
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test(expected = IndexOutOfBoundsException.class) @Test
public void subInput1PositiveNegativePositiveOutputArrayIndexOutOfBoundsException() { public void subInput1PositiveNegativePositiveOutputArrayIndexOutOfBoundsException() {
// Arrange assertThrows(IndexOutOfBoundsException.class, () -> {
final List<Integer> list = new ArrayList<>(); // Arrange
list.add(null); final List<Integer> list = new ArrayList<>();
final int start = 2_147_483_643; list.add(null);
final int end = -2_147_483_648; final int start = 2_147_483_643;
final int step = 2; final int end = -2_147_483_648;
final int step = 2;
// Act // Act
CollUtil.sub(list, start, end, step); CollUtil.sub(list, start, end, step);
// Method is not expected to return due to exception thrown // Method is not expected to return due to exception thrown
});
} }
@Test @Test
@ -636,7 +636,7 @@ public class CollUtilTest {
// Act // Act
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
Assert.assertTrue(retval.isEmpty()); assertTrue(retval.isEmpty());
} }
@Test @Test
@ -651,7 +651,7 @@ public class CollUtilTest {
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -666,7 +666,7 @@ public class CollUtilTest {
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -681,7 +681,7 @@ public class CollUtilTest {
final List<Integer> retval = CollUtil.sub(list, start, end, step); final List<Integer> retval = CollUtil.sub(list, start, end, step);
// Assert result // Assert result
final List<Integer> arrayList = new ArrayList<>(); final List<Integer> arrayList = new ArrayList<>();
Assert.assertEquals(arrayList, retval); assertEquals(arrayList, retval);
} }
@Test @Test
@ -693,7 +693,7 @@ public class CollUtilTest {
// Act // Act
final List<Integer> retval = CollUtil.sub(list, start, end); final List<Integer> retval = CollUtil.sub(list, start, end);
// Assert result // Assert result
Assert.assertTrue(retval.isEmpty()); assertTrue(retval.isEmpty());
} }
@Test @Test
@ -701,7 +701,7 @@ public class CollUtilTest {
final List<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9); final List<Integer> list = CollUtil.newArrayList(1, 2, 3, 4, 5, 6, 7, 8, 9);
final List<Integer> sortPageAll = CollUtil.sortPageAll(1, 5, Comparator.reverseOrder(), list); final List<Integer> sortPageAll = CollUtil.sortPageAll(1, 5, Comparator.reverseOrder(), list);
Assert.assertEquals(CollUtil.newArrayList(4, 3, 2, 1), sortPageAll); assertEquals(CollUtil.newArrayList(4, 3, 2, 1), sortPageAll);
} }
@Test @Test
@ -709,18 +709,18 @@ public class CollUtilTest {
final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5); final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5);
final ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1, 9, 11); final ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1, 9, 11);
Assert.assertTrue(CollUtil.containsAny(list1, list2)); assertTrue(CollUtil.containsAny(list1, list2));
} }
@Test @Test
public void containsAllTest() { public void containsAllTest() {
final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5); final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4, 5);
final ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1); final ArrayList<Integer> list2 = CollUtil.newArrayList(5, 3, 1);
Assert.assertTrue(CollUtil.containsAll(list1, list2)); assertTrue(CollUtil.containsAll(list1, list2));
final ArrayList<Integer> list3 = CollUtil.newArrayList(1); final ArrayList<Integer> list3 = CollUtil.newArrayList(1);
final ArrayList<Integer> list4 = CollUtil.newArrayList(); final ArrayList<Integer> list4 = CollUtil.newArrayList();
Assert.assertTrue(CollUtil.containsAll(list3, list4)); assertTrue(CollUtil.containsAll(list3, list4));
} }
@Test @Test
@ -728,7 +728,7 @@ public class CollUtilTest {
// 测试空数组返回null而不是报错 // 测试空数组返回null而不是报错
final List<String> test = CollUtil.newArrayList(); final List<String> test = CollUtil.newArrayList();
final String last = CollUtil.getLast(test); final String last = CollUtil.getLast(test);
Assert.assertNull(last); assertNull(last);
} }
@Test @Test
@ -738,39 +738,39 @@ public class CollUtilTest {
final Map<String, Integer> map = CollUtil.zip(keys, values); final Map<String, Integer> map = CollUtil.zip(keys, values);
Assert.assertEquals(4, Objects.requireNonNull(map).size()); assertEquals(4, Objects.requireNonNull(map).size());
Assert.assertEquals(1, map.get("a").intValue()); assertEquals(1, map.get("a").intValue());
Assert.assertEquals(2, map.get("b").intValue()); assertEquals(2, map.get("b").intValue());
Assert.assertEquals(3, map.get("c").intValue()); assertEquals(3, map.get("c").intValue());
Assert.assertEquals(4, map.get("d").intValue()); assertEquals(4, map.get("d").intValue());
} }
@Test @Test
public void toMapTest() { public void toMapTest() {
final Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d"); final Collection<String> keys = CollUtil.newArrayList("a", "b", "c", "d");
final Map<String, String> map = CollUtil.toMap(keys, new HashMap<>(), (value) -> "key" + value); final Map<String, String> map = CollUtil.toMap(keys, new HashMap<>(), (value) -> "key" + value);
Assert.assertEquals("a", map.get("keya")); assertEquals("a", map.get("keya"));
Assert.assertEquals("b", map.get("keyb")); assertEquals("b", map.get("keyb"));
Assert.assertEquals("c", map.get("keyc")); assertEquals("c", map.get("keyc"));
Assert.assertEquals("d", map.get("keyd")); assertEquals("d", map.get("keyd"));
} }
@Test @Test
public void addIfAbsentTest() { public void addIfAbsentTest() {
// 为false的情况 // 为false的情况
Assert.assertFalse(CollUtil.addIfAbsent(null, null)); assertFalse(CollUtil.addIfAbsent(null, null));
Assert.assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList(), null)); assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList(), null));
Assert.assertFalse(CollUtil.addIfAbsent(null, "123")); assertFalse(CollUtil.addIfAbsent(null, "123"));
Assert.assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList("123"), "123")); assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList("123"), "123"));
Assert.assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)), assertFalse(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)),
new Animal("jack", 20))); new Animal("jack", 20)));
// 正常情况 // 正常情况
Assert.assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList("456"), "123")); assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList("456"), "123"));
Assert.assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)), assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)),
new Dog("jack", 20))); new Dog("jack", 20)));
Assert.assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)), assertTrue(CollUtil.addIfAbsent(CollUtil.newArrayList(new Animal("jack", 20)),
new Animal("tom", 20))); new Animal("tom", 20)));
} }
@ -786,9 +786,9 @@ public class CollUtilTest {
Map.Entry::getKey, Map.Entry::getKey,
entry -> Long.parseLong(entry.getValue())); entry -> Long.parseLong(entry.getValue()));
Assert.assertEquals(1L, (long) map.get("a")); assertEquals(1L, (long) map.get("a"));
Assert.assertEquals(12L, (long) map.get("b")); assertEquals(12L, (long) map.get("b"));
Assert.assertEquals(134L, (long) map.get("c")); assertEquals(134L, (long) map.get("c"));
} }
@Test @Test
@ -796,17 +796,17 @@ public class CollUtilTest {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d"); final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d");
final Map<String, Integer> countMap = CollUtil.countMap(list); final Map<String, Integer> countMap = CollUtil.countMap(list);
Assert.assertEquals(Integer.valueOf(2), countMap.get("a")); assertEquals(Integer.valueOf(2), countMap.get("a"));
Assert.assertEquals(Integer.valueOf(2), countMap.get("b")); assertEquals(Integer.valueOf(2), countMap.get("b"));
Assert.assertEquals(Integer.valueOf(2), countMap.get("c")); assertEquals(Integer.valueOf(2), countMap.get("c"));
Assert.assertEquals(Integer.valueOf(1), countMap.get("d")); assertEquals(Integer.valueOf(1), countMap.get("d"));
} }
@Test @Test
public void indexOfTest() { public void indexOfTest() {
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d"); final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d");
final int i = CollUtil.indexOf(list, (str) -> str.charAt(0) == 'c'); final int i = CollUtil.indexOf(list, (str) -> str.charAt(0) == 'c');
Assert.assertEquals(2, i); assertEquals(2, i);
} }
@Test @Test
@ -814,7 +814,7 @@ public class CollUtilTest {
// List有优化 // List有优化
final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d"); final ArrayList<String> list = CollUtil.newArrayList("a", "b", "c", "c", "a", "b", "d");
final int i = CollUtil.lastIndexOf(list, (str) -> str.charAt(0) == 'c'); final int i = CollUtil.lastIndexOf(list, (str) -> str.charAt(0) == 'c');
Assert.assertEquals(3, i); assertEquals(3, i);
} }
@Test @Test
@ -822,7 +822,7 @@ public class CollUtilTest {
final Set<String> list = CollUtil.set(true, "a", "b", "c", "c", "a", "b", "d"); final Set<String> list = CollUtil.set(true, "a", "b", "c", "c", "a", "b", "d");
// 去重后c排第三 // 去重后c排第三
final int i = CollUtil.lastIndexOf(list, (str) -> str.charAt(0) == 'c'); final int i = CollUtil.lastIndexOf(list, (str) -> str.charAt(0) == 'c');
Assert.assertEquals(2, i); assertEquals(2, i);
} }
@Test @Test
@ -832,7 +832,7 @@ public class CollUtilTest {
objects.add(Dict.create().set("name", "姓名:" + i)); objects.add(Dict.create().set("name", "姓名:" + i));
} }
Assert.assertEquals(0, CollUtil.page(3, 5, objects).size()); assertEquals(0, CollUtil.page(3, 5, objects).size());
} }
@Test @Test
@ -841,15 +841,15 @@ public class CollUtilTest {
final List<Long> list2 = Arrays.asList(2L, 3L); final List<Long> list2 = Arrays.asList(2L, 3L);
final List<Long> result = CollUtil.subtractToList(list1, list2); final List<Long> result = CollUtil.subtractToList(list1, list2);
Assert.assertEquals(1, result.size()); assertEquals(1, result.size());
Assert.assertEquals(1L, (long) result.get(0)); assertEquals(1L, (long) result.get(0));
} }
@Test @Test
public void sortComparableTest() { public void sortComparableTest() {
final List<String> of = ListUtil.toList("a", "c", "b"); final List<String> of = ListUtil.toList("a", "c", "b");
final List<String> sort = CollUtil.sort(of, new ComparableComparator<>()); final List<String> sort = CollUtil.sort(of, new ComparableComparator<>());
Assert.assertEquals("a,b,c", CollUtil.join(sort, ",")); assertEquals("a,b,c", CollUtil.join(sort, ","));
} }
@Test @Test
@ -872,9 +872,9 @@ public class CollUtilTest {
genderMap.put(5, "小孩"); genderMap.put(5, "小孩");
genderMap.put(6, ""); genderMap.put(6, "");
Assert.assertEquals(people.get(1).getGender(), "woman"); assertEquals(people.get(1).getGender(), "woman");
CollUtil.setValueByMap(people, genderMap, Person::getId, Person::setGender); CollUtil.setValueByMap(people, genderMap, Person::getId, Person::setGender);
Assert.assertEquals(people.get(1).getGender(), "妇女"); assertEquals(people.get(1).getGender(), "妇女");
final Map<Integer, Person> personMap = new HashMap<>(); final Map<Integer, Person> personMap = new HashMap<>();
personMap.put(1, new Person("AA", 21, "", 1)); personMap.put(1, new Person("AA", 21, "", 1));
@ -890,13 +890,13 @@ public class CollUtilTest {
x.setAge(y.getAge()); x.setAge(y.getAge());
}); });
Assert.assertEquals(people.get(1).getGender(), "小孩"); assertEquals(people.get(1).getGender(), "小孩");
} }
@Test @Test
public void distinctTest() { public void distinctTest() {
final ArrayList<Integer> distinct = CollUtil.distinct(ListUtil.of(5, 3, 10, 9, 0, 5, 10, 9)); final ArrayList<Integer> distinct = CollUtil.distinct(ListUtil.of(5, 3, 10, 9, 0, 5, 10, 9));
Assert.assertEquals(ListUtil.of(5, 3, 10, 9, 0), distinct); assertEquals(ListUtil.of(5, 3, 10, 9, 0), distinct);
} }
@Test @Test
@ -912,15 +912,15 @@ public class CollUtilTest {
// 覆盖模式下ff覆盖了aaee覆盖了bb // 覆盖模式下ff覆盖了aaee覆盖了bb
List<Person> distinct = CollUtil.distinct(people, Person::getGender, true); List<Person> distinct = CollUtil.distinct(people, Person::getGender, true);
Assert.assertEquals(2, distinct.size()); assertEquals(2, distinct.size());
Assert.assertEquals("ff", distinct.get(0).getName()); assertEquals("ff", distinct.get(0).getName());
Assert.assertEquals("ee", distinct.get(1).getName()); assertEquals("ee", distinct.get(1).getName());
// 非覆盖模式下保留了最早加入的aa和bb // 非覆盖模式下保留了最早加入的aa和bb
distinct = CollUtil.distinct(people, Person::getGender, false); distinct = CollUtil.distinct(people, Person::getGender, false);
Assert.assertEquals(2, distinct.size()); assertEquals(2, distinct.size());
Assert.assertEquals("aa", distinct.get(0).getName()); assertEquals("aa", distinct.get(0).getName());
Assert.assertEquals("bb", distinct.get(1).getName()); assertEquals("bb", distinct.get(1).getName());
} }
@SuppressWarnings("ConstantValue") @SuppressWarnings("ConstantValue")
@ -930,7 +930,7 @@ public class CollUtilTest {
final List<String> list2 = null; final List<String> list2 = null;
final List<String> list3 = null; final List<String> list3 = null;
final Collection<String> union = CollUtil.union(list1, list2, list3); final Collection<String> union = CollUtil.union(list1, list2, list3);
Assert.assertNotNull(union); assertNotNull(union);
} }
@SuppressWarnings("ConstantValue") @SuppressWarnings("ConstantValue")
@ -940,7 +940,7 @@ public class CollUtilTest {
final List<String> list2 = null; final List<String> list2 = null;
final List<String> list3 = null; final List<String> list3 = null;
final Set<String> set = CollUtil.unionDistinct(list1, list2, list3); final Set<String> set = CollUtil.unionDistinct(list1, list2, list3);
Assert.assertNotNull(set); assertNotNull(set);
} }
@SuppressWarnings({"ConfusingArgumentToVarargsMethod", "ConstantValue"}) @SuppressWarnings({"ConfusingArgumentToVarargsMethod", "ConstantValue"})
@ -950,10 +950,10 @@ public class CollUtilTest {
final List<String> list2 = null; final List<String> list2 = null;
final List<String> list3 = null; final List<String> list3 = null;
final List<String> list = CollUtil.unionAll(list1, list2, list3); final List<String> list = CollUtil.unionAll(list1, list2, list3);
Assert.assertNotNull(list); assertNotNull(list);
final List<String> resList2 = CollUtil.unionAll(null, null, null); final List<String> resList2 = CollUtil.unionAll(null, null, null);
Assert.assertNotNull(resList2); assertNotNull(resList2);
} }
@Test @Test
@ -962,8 +962,8 @@ public class CollUtilTest {
final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3); final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3);
final List<Integer> list3 = CollectionUtil.newArrayList(4, 5, 6); final List<Integer> list3 = CollectionUtil.newArrayList(4, 5, 6);
final List<Integer> list = CollUtil.unionAll(list1, list2, list3); final List<Integer> list = CollUtil.unionAll(list1, list2, list3);
Assert.assertNotNull(list); assertNotNull(list);
Assert.assertArrayEquals( assertArrayEquals(
CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3, 4, 5, 6).toArray(), CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3, 4, 5, 6).toArray(),
list.toArray()); list.toArray());
} }
@ -973,8 +973,8 @@ public class CollUtilTest {
final List<Integer> list1 = CollectionUtil.newArrayList(1, 2, 2, 3, 3); final List<Integer> list1 = CollectionUtil.newArrayList(1, 2, 2, 3, 3);
final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3); final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3);
final List<Integer> list = CollUtil.unionAll(list1, list2); final List<Integer> list = CollUtil.unionAll(list1, list2);
Assert.assertNotNull(list); assertNotNull(list);
Assert.assertArrayEquals( assertArrayEquals(
CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3).toArray(), CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3).toArray(),
list.toArray()); list.toArray());
} }
@ -984,8 +984,8 @@ public class CollUtilTest {
final List<Integer> list1 = CollectionUtil.newArrayList(1, 2, 2, 3, 3); final List<Integer> list1 = CollectionUtil.newArrayList(1, 2, 2, 3, 3);
final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3); final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3);
@SuppressWarnings("ConfusingArgumentToVarargsMethod") final List<Integer> list = CollUtil.unionAll(list1, list2, null); @SuppressWarnings("ConfusingArgumentToVarargsMethod") final List<Integer> list = CollUtil.unionAll(list1, list2, null);
Assert.assertNotNull(list); assertNotNull(list);
Assert.assertArrayEquals( assertArrayEquals(
CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3).toArray(), CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3).toArray(),
list.toArray()); list.toArray());
} }
@ -995,8 +995,8 @@ public class CollUtilTest {
final List<Integer> list1 = CollectionUtil.newArrayList(1, 2, 2, 3, 3); final List<Integer> list1 = CollectionUtil.newArrayList(1, 2, 2, 3, 3);
final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3); final List<Integer> list2 = CollectionUtil.newArrayList(1, 2, 3);
final List<Integer> list = CollUtil.unionAll(list1, list2, null, null); final List<Integer> list = CollUtil.unionAll(list1, list2, null, null);
Assert.assertNotNull(list); assertNotNull(list);
Assert.assertArrayEquals( assertArrayEquals(
CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3).toArray(), CollectionUtil.newArrayList(1, 2, 2, 3, 3, 1, 2, 3).toArray(),
list.toArray()); list.toArray());
} }
@ -1010,7 +1010,7 @@ public class CollUtilTest {
list2.add("aa"); list2.add("aa");
final List<String> list3 = null; final List<String> list3 = null;
final Collection<String> collection = CollUtil.intersection(list1, list2, list3); final Collection<String> collection = CollUtil.intersection(list1, list2, list3);
Assert.assertNotNull(collection); assertNotNull(collection);
} }
@Test @Test
@ -1021,7 +1021,7 @@ public class CollUtilTest {
// list2.add("aa"); // list2.add("aa");
final List<String> list3 = null; final List<String> list3 = null;
final Collection<String> collection = CollUtil.intersectionDistinct(list1, list2, list3); final Collection<String> collection = CollUtil.intersectionDistinct(list1, list2, list3);
Assert.assertNotNull(collection); assertNotNull(collection);
} }
@Data @Data
@ -1055,33 +1055,34 @@ public class CollUtilTest {
public void getFirstTest() { public void getFirstTest() {
final List<?> nullList = null; final List<?> nullList = null;
final Object first = CollUtil.getFirst(nullList); final Object first = CollUtil.getFirst(nullList);
Assert.assertNull(first); assertNull(first);
} }
@Test @Test
public void testMatch() { public void testMatch() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Assert.assertTrue(CollUtil.anyMatch(list, i -> i == 1)); assertTrue(CollUtil.anyMatch(list, i -> i == 1));
Assert.assertFalse(CollUtil.anyMatch(list, i -> i > 6)); assertFalse(CollUtil.anyMatch(list, i -> i > 6));
Assert.assertFalse(CollUtil.allMatch(list, i -> i == 1)); assertFalse(CollUtil.allMatch(list, i -> i == 1));
Assert.assertTrue(CollUtil.allMatch(list, i -> i <= 6)); assertTrue(CollUtil.allMatch(list, i -> i <= 6));
} }
@Test @Test
public void maxTest() { public void maxTest() {
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6); List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6);
Assert.assertEquals((Integer) 6, CollUtil.max(list)); assertEquals((Integer) 6, CollUtil.max(list));
} }
@SuppressWarnings({"rawtypes", "unchecked"})
@Test @Test
public void maxEmptyTest() { public void maxEmptyTest() {
final List<? extends Comparable> emptyList = Collections.emptyList(); final List<? extends Comparable> emptyList = Collections.emptyList();
Assert.assertNull(CollUtil.max(emptyList)); assertNull(CollUtil.max(emptyList));
} }
@Test @Test
public void minNullTest() { public void minNullTest() {
Assert.assertNull(CollUtil.max(null)); assertNull(CollUtil.max(null));
} }
@Test @Test
@ -1098,6 +1099,6 @@ public class CollUtilTest {
coll2.add("1"); coll2.add("1");
coll2.add("1"); coll2.add("1");
Assert.assertTrue(CollUtil.containsAll(coll1, coll2)); assertTrue(CollUtil.containsAll(coll1, coll2));
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.collection; package cn.hutool.core.collection;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Iterator; import java.util.Iterator;
@ -23,7 +23,7 @@ public class FilterIterTest {
count++; count++;
} }
} }
Assert.assertEquals(2, count); assertEquals(2, count);
it = ListUtil.of("1", "2").iterator(); it = ListUtil.of("1", "2").iterator();
// filter 不为空 // filter 不为空
@ -34,7 +34,7 @@ public class FilterIterTest {
count++; count++;
} }
} }
Assert.assertEquals(1, count); assertEquals(1, count);
} }
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.collection;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayDeque; import java.util.ArrayDeque;
import java.util.ArrayList; import java.util.ArrayList;
@ -23,20 +23,20 @@ public class IterUtilTest {
@Test @Test
public void getFirstTest() { public void getFirstTest() {
Assert.assertNull(IterUtil.getFirst((Iterable<Object>) null)); assertNull(IterUtil.getFirst((Iterable<Object>) null));
Assert.assertNull(IterUtil.getFirst(CollUtil.newArrayList())); assertNull(IterUtil.getFirst(CollUtil.newArrayList()));
Assert.assertEquals("1", IterUtil.getFirst(CollUtil.newArrayList("1", "2", "3"))); assertEquals("1", IterUtil.getFirst(CollUtil.newArrayList("1", "2", "3")));
final ArrayDeque<String> deque = new ArrayDeque<>(); final ArrayDeque<String> deque = new ArrayDeque<>();
deque.add("3"); deque.add("3");
deque.add("4"); deque.add("4");
Assert.assertEquals("3", IterUtil.getFirst(deque)); assertEquals("3", IterUtil.getFirst(deque));
} }
@Test @Test
public void getFirstNonNullTest(){ public void getFirstNonNullTest(){
final ArrayList<String> strings = CollUtil.newArrayList(null, null, "123", "456", null); final ArrayList<String> strings = CollUtil.newArrayList(null, null, "123", "456", null);
Assert.assertEquals("123", IterUtil.getFirstNoneNull(strings)); assertEquals("123", IterUtil.getFirstNoneNull(strings));
} }
@Test @Test
@ -44,39 +44,39 @@ public class IterUtilTest {
final ArrayList<Car> carList = CollUtil.newArrayList(new Car("123", "大众"), new Car("345", "奔驰"), new Car("567", "路虎")); final ArrayList<Car> carList = CollUtil.newArrayList(new Car("123", "大众"), new Car("345", "奔驰"), new Car("567", "路虎"));
final Map<String, Car> carNameMap = IterUtil.fieldValueMap(carList.iterator(), "carNumber"); final Map<String, Car> carNameMap = IterUtil.fieldValueMap(carList.iterator(), "carNumber");
Assert.assertEquals("大众", carNameMap.get("123").getCarName()); assertEquals("大众", carNameMap.get("123").getCarName());
Assert.assertEquals("奔驰", carNameMap.get("345").getCarName()); assertEquals("奔驰", carNameMap.get("345").getCarName());
Assert.assertEquals("路虎", carNameMap.get("567").getCarName()); assertEquals("路虎", carNameMap.get("567").getCarName());
} }
@Test @Test
public void joinTest() { public void joinTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", "2", "3", "4"); final ArrayList<String> list = CollUtil.newArrayList("1", "2", "3", "4");
final String join = IterUtil.join(list.iterator(), ":"); final String join = IterUtil.join(list.iterator(), ":");
Assert.assertEquals("1:2:3:4", join); assertEquals("1:2:3:4", join);
final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4); final ArrayList<Integer> list1 = CollUtil.newArrayList(1, 2, 3, 4);
final String join1 = IterUtil.join(list1.iterator(), ":"); final String join1 = IterUtil.join(list1.iterator(), ":");
Assert.assertEquals("1:2:3:4", join1); assertEquals("1:2:3:4", join1);
// 包装每个节点 // 包装每个节点
final ArrayList<String> list2 = CollUtil.newArrayList("1", "2", "3", "4"); final ArrayList<String> list2 = CollUtil.newArrayList("1", "2", "3", "4");
final String join2 = IterUtil.join(list2.iterator(), ":", "\"", "\""); final String join2 = IterUtil.join(list2.iterator(), ":", "\"", "\"");
Assert.assertEquals("\"1\":\"2\":\"3\":\"4\"", join2); assertEquals("\"1\":\"2\":\"3\":\"4\"", join2);
} }
@Test @Test
public void joinWithFuncTest() { public void joinWithFuncTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", "2", "3", "4"); final ArrayList<String> list = CollUtil.newArrayList("1", "2", "3", "4");
final String join = IterUtil.join(list.iterator(), ":", String::valueOf); final String join = IterUtil.join(list.iterator(), ":", String::valueOf);
Assert.assertEquals("1:2:3:4", join); assertEquals("1:2:3:4", join);
} }
@Test @Test
public void joinWithNullTest() { public void joinWithNullTest() {
final ArrayList<String> list = CollUtil.newArrayList("1", null, "3", "4"); final ArrayList<String> list = CollUtil.newArrayList("1", null, "3", "4");
final String join = IterUtil.join(list.iterator(), ":", String::valueOf); final String join = IterUtil.join(list.iterator(), ":", String::valueOf);
Assert.assertEquals("1:null:3:4", join); assertEquals("1:null:3:4", join);
} }
@Test @Test
@ -87,7 +87,7 @@ public class IterUtilTest {
final Map<String, List<String>> testMap = IterUtil.toListMap(Arrays.asList("and", "brave", "back"), final Map<String, List<String>> testMap = IterUtil.toListMap(Arrays.asList("and", "brave", "back"),
v -> v.substring(0, 1)); v -> v.substring(0, 1));
Assert.assertEquals(testMap, expectedMap); assertEquals(testMap, expectedMap);
} }
@Test @Test
@ -101,14 +101,14 @@ public class IterUtilTest {
expectedMap.put("456", benz); expectedMap.put("456", benz);
final Map<String, Car> testMap = IterUtil.toMap(Arrays.asList(bmw, benz), Car::getCarNumber); final Map<String, Car> testMap = IterUtil.toMap(Arrays.asList(bmw, benz), Car::getCarNumber);
Assert.assertEquals(expectedMap, testMap); assertEquals(expectedMap, testMap);
} }
@Test @Test
public void getElementTypeTest(){ public void getElementTypeTest(){
final List<Integer> integers = Arrays.asList(null, 1); final List<Integer> integers = Arrays.asList(null, 1);
final Class<?> elementType = IterUtil.getElementType(integers); final Class<?> elementType = IterUtil.getElementType(integers);
Assert.assertEquals(Integer.class,elementType); assertEquals(Integer.class,elementType);
} }
@Data @Data
@ -125,8 +125,8 @@ public class IterUtilTest {
IterUtil.filter(obj.iterator(), obj2::contains); IterUtil.filter(obj.iterator(), obj2::contains);
Assert.assertEquals(1, obj.size()); assertEquals(1, obj.size());
Assert.assertEquals("3", obj.get(0)); assertEquals("3", obj.get(0));
} }
@Test @Test
@ -136,8 +136,8 @@ public class IterUtilTest {
final FilterIter<String> filtered = IterUtil.filtered(obj.iterator(), obj2::contains); final FilterIter<String> filtered = IterUtil.filtered(obj.iterator(), obj2::contains);
Assert.assertEquals("3", filtered.next()); assertEquals("3", filtered.next());
Assert.assertFalse(filtered.hasNext()); assertFalse(filtered.hasNext());
} }
@Test @Test
@ -147,14 +147,14 @@ public class IterUtilTest {
final List<String> filtered = IterUtil.filterToList(obj.iterator(), obj2::contains); final List<String> filtered = IterUtil.filterToList(obj.iterator(), obj2::contains);
Assert.assertEquals(1, filtered.size()); assertEquals(1, filtered.size());
Assert.assertEquals("3", filtered.get(0)); assertEquals("3", filtered.get(0));
} }
@Test @Test
public void getTest() { public void getTest() {
final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D"); final HashSet<String> set = CollUtil.set(true, "A", "B", "C", "D");
final String str = IterUtil.get(set.iterator(), 2); final String str = IterUtil.get(set.iterator(), 2);
Assert.assertEquals("C", str); assertEquals("C", str);
} }
} }

View File

@ -6,17 +6,12 @@ import cn.hutool.core.util.PageUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import org.junit.jupiter.api.Disabled;
import org.junit.Ignore; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.util.ArrayList; import java.util.*;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import static org.junit.Assert.assertEquals; import static org.junit.jupiter.api.Assertions.*;
public class ListUtilTest { public class ListUtilTest {
@ -38,7 +33,7 @@ public class ListUtilTest {
} }
@Test @Test
@Ignore @Disabled
public void splitBenchTest() { public void splitBenchTest() {
final List<String> list = new ArrayList<>(); final List<String> list = new ArrayList<>();
CollUtil.padRight(list, RandomUtil.randomInt(1000_0000, 1_0000_0000), "test"); CollUtil.padRight(list, RandomUtil.randomInt(1000_0000, 1_0000_0000), "test");
@ -85,10 +80,12 @@ public class ListUtilTest {
assertEquals("[[1], [2], [3], [], []]", lists.toString()); assertEquals("[[1], [2], [3], [], []]", lists.toString());
} }
@Test(expected = IllegalArgumentException.class) @Test
public void splitAvgNotZero() { public void splitAvgNotZero() {
// limit不能小于等于0 assertThrows(IllegalArgumentException.class, () -> {
ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 0); // limit不能小于等于0
ListUtil.splitAvg(Arrays.asList(1, 2, 3, 4), 0);
});
} }
@Test @Test
@ -104,63 +101,63 @@ public class ListUtilTest {
public void indexOfAll() { public void indexOfAll() {
final List<String> a = ListUtil.toLinkedList("1", "2", "3", "4", "3", "2", "1"); final List<String> a = ListUtil.toLinkedList("1", "2", "3", "4", "3", "2", "1");
final int[] indexArray = ListUtil.indexOfAll(a, "2"::equals); final int[] indexArray = ListUtil.indexOfAll(a, "2"::equals);
Assert.assertArrayEquals(new int[]{1,5}, indexArray); assertArrayEquals(new int[]{1, 5}, indexArray);
final int[] indexArray2 = ListUtil.indexOfAll(a, "1"::equals); final int[] indexArray2 = ListUtil.indexOfAll(a, "1"::equals);
Assert.assertArrayEquals(new int[]{0,6}, indexArray2); assertArrayEquals(new int[]{0, 6}, indexArray2);
} }
@Test @Test
public void pageTest() { public void pageTest() {
final List<Integer> a = ListUtil.toLinkedList(1, 2, 3,4,5); final List<Integer> a = ListUtil.toLinkedList(1, 2, 3, 4, 5);
PageUtil.setFirstPageNo(1); PageUtil.setFirstPageNo(1);
final int[] a_1 = ListUtil.page(1,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] a_1 = ListUtil.page(1, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] a1 = ListUtil.page(1,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] a1 = ListUtil.page(1, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] a2 = ListUtil.page(2,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] a2 = ListUtil.page(2, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] a3 = ListUtil.page(3,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] a3 = ListUtil.page(3, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] a4 = ListUtil.page(4,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] a4 = ListUtil.page(4, 2, a).stream().mapToInt(Integer::valueOf).toArray();
Assert.assertArrayEquals(new int[]{1,2},a_1); assertArrayEquals(new int[]{1, 2}, a_1);
Assert.assertArrayEquals(new int[]{1,2},a1); assertArrayEquals(new int[]{1, 2}, a1);
Assert.assertArrayEquals(new int[]{3,4},a2); assertArrayEquals(new int[]{3, 4}, a2);
Assert.assertArrayEquals(new int[]{5},a3); assertArrayEquals(new int[]{5}, a3);
Assert.assertArrayEquals(new int[]{},a4); assertArrayEquals(new int[]{}, a4);
PageUtil.setFirstPageNo(2); PageUtil.setFirstPageNo(2);
final int[] b_1 = ListUtil.page(1,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] b_1 = ListUtil.page(1, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] b1 = ListUtil.page(2,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] b1 = ListUtil.page(2, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] b2 = ListUtil.page(3,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] b2 = ListUtil.page(3, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] b3 = ListUtil.page(4,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] b3 = ListUtil.page(4, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] b4 = ListUtil.page(5,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] b4 = ListUtil.page(5, 2, a).stream().mapToInt(Integer::valueOf).toArray();
Assert.assertArrayEquals(new int[]{1,2},b_1); assertArrayEquals(new int[]{1, 2}, b_1);
Assert.assertArrayEquals(new int[]{1,2},b1); assertArrayEquals(new int[]{1, 2}, b1);
Assert.assertArrayEquals(new int[]{3,4},b2); assertArrayEquals(new int[]{3, 4}, b2);
Assert.assertArrayEquals(new int[]{5},b3); assertArrayEquals(new int[]{5}, b3);
Assert.assertArrayEquals(new int[]{},b4); assertArrayEquals(new int[]{}, b4);
PageUtil.setFirstPageNo(0); PageUtil.setFirstPageNo(0);
final int[] c_1 = ListUtil.page(-1,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] c_1 = ListUtil.page(-1, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] c1 = ListUtil.page(0,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] c1 = ListUtil.page(0, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] c2 = ListUtil.page(1,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] c2 = ListUtil.page(1, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] c3 = ListUtil.page(2,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] c3 = ListUtil.page(2, 2, a).stream().mapToInt(Integer::valueOf).toArray();
final int[] c4 = ListUtil.page(3,2,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] c4 = ListUtil.page(3, 2, a).stream().mapToInt(Integer::valueOf).toArray();
Assert.assertArrayEquals(new int[]{1,2},c_1); assertArrayEquals(new int[]{1, 2}, c_1);
Assert.assertArrayEquals(new int[]{1,2},c1); assertArrayEquals(new int[]{1, 2}, c1);
Assert.assertArrayEquals(new int[]{3,4},c2); assertArrayEquals(new int[]{3, 4}, c2);
Assert.assertArrayEquals(new int[]{5},c3); assertArrayEquals(new int[]{5}, c3);
Assert.assertArrayEquals(new int[]{},c4); assertArrayEquals(new int[]{}, c4);
PageUtil.setFirstPageNo(1); PageUtil.setFirstPageNo(1);
final int[] d1 = ListUtil.page(0,8,a).stream().mapToInt(Integer::valueOf).toArray(); final int[] d1 = ListUtil.page(0, 8, a).stream().mapToInt(Integer::valueOf).toArray();
Assert.assertArrayEquals(new int[]{1,2,3,4,5},d1); assertArrayEquals(new int[]{1, 2, 3, 4, 5}, d1);
// page with consumer // page with consumer
final List<List<Integer>> pageListData = new ArrayList<>(); final List<List<Integer>> pageListData = new ArrayList<>();
ListUtil.page(a, 2, pageListData::add); ListUtil.page(a, 2, pageListData::add);
Assert.assertArrayEquals(new int[]{1, 2}, pageListData.get(0).stream().mapToInt(Integer::valueOf).toArray()); assertArrayEquals(new int[]{1, 2}, pageListData.get(0).stream().mapToInt(Integer::valueOf).toArray());
Assert.assertArrayEquals(new int[]{3, 4}, pageListData.get(1).stream().mapToInt(Integer::valueOf).toArray()); 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()); assertArrayEquals(new int[]{5}, pageListData.get(2).stream().mapToInt(Integer::valueOf).toArray());
pageListData.clear(); pageListData.clear();
@ -170,9 +167,9 @@ public class ListUtilTest {
pageList.clear(); pageList.clear();
} }
}); });
Assert.assertArrayEquals(new int[]{}, pageListData.get(0).stream().mapToInt(Integer::valueOf).toArray()); 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()); 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()); assertArrayEquals(new int[]{5}, pageListData.get(2).stream().mapToInt(Integer::valueOf).toArray());
// 恢复默认值避免影响其他测试用例 // 恢复默认值避免影响其他测试用例
PageUtil.setFirstPageNo(0); PageUtil.setFirstPageNo(0);
@ -199,12 +196,12 @@ public class ListUtilTest {
} }
final List<TestBean> beanList = ListUtil.toList( final List<TestBean> beanList = ListUtil.toList(
new TestBean(2, "test2"), new TestBean(2, "test2"),
new TestBean(1, "test1"), new TestBean(1, "test1"),
new TestBean(5, "test5"), new TestBean(5, "test5"),
new TestBean(4, "test4"), new TestBean(4, "test4"),
new TestBean(3, "test3") new TestBean(3, "test3")
); );
final List<TestBean> order = ListUtil.sortByProperty(beanList, "order"); final List<TestBean> order = ListUtil.sortByProperty(beanList, "order");
assertEquals("test1", order.get(0).getName()); assertEquals("test1", order.get(0).getName());
@ -240,7 +237,7 @@ public class ListUtilTest {
} }
@Test @Test
public void setOrPaddingNullTest(){ public void setOrPaddingNullTest() {
final List<String> list = new ArrayList<>(); final List<String> list = new ArrayList<>();
list.add("1"); list.add("1");

View File

@ -5,8 +5,8 @@ import java.util.Map;
import java.util.Map.Entry; import java.util.Map.Entry;
import java.util.Set; import java.util.Set;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import cn.hutool.core.map.MapProxy; import cn.hutool.core.map.MapProxy;
@ -20,13 +20,13 @@ public class MapProxyTest {
MapProxy mapProxy = new MapProxy(map); MapProxy mapProxy = new MapProxy(map);
Integer b = mapProxy.getInt("b"); Integer b = mapProxy.getInt("b");
Assert.assertEquals(new Integer(2), b); assertEquals(new Integer(2), b);
Set<Object> keys = mapProxy.keySet(); Set<Object> keys = mapProxy.keySet();
Assert.assertFalse(keys.isEmpty()); assertFalse(keys.isEmpty());
Set<Entry<Object,Object>> entrys = mapProxy.entrySet(); Set<Entry<Object,Object>> entrys = mapProxy.entrySet();
Assert.assertFalse(entrys.isEmpty()); assertFalse(entrys.isEmpty());
} }
private interface Student { private interface Student {
@ -41,7 +41,7 @@ public class MapProxyTest {
public void classProxyTest() { public void classProxyTest() {
Student student = MapProxy.create(new HashMap<>()).toProxyBean(Student.class); Student student = MapProxy.create(new HashMap<>()).toProxyBean(Student.class);
student.setName("小明").setAge(18); student.setName("小明").setAge(18);
Assert.assertEquals(student.getAge(), 18); assertEquals(student.getAge(), 18);
Assert.assertEquals(student.getName(), "小明"); assertEquals(student.getName(), "小明");
} }
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.collection;
import cn.hutool.core.io.resource.ResourceUtil; import cn.hutool.core.io.resource.ResourceUtil;
import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.NumberUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
@ -14,7 +14,7 @@ public class PartitionIterTest {
final LineIter lineIter = new LineIter(ResourceUtil.getUtf8Reader("test_lines.csv")); final LineIter lineIter = new LineIter(ResourceUtil.getUtf8Reader("test_lines.csv"));
final PartitionIter<String> iter = new PartitionIter<>(lineIter, 3); final PartitionIter<String> iter = new PartitionIter<>(lineIter, 3);
for (List<String> lines : iter) { for (List<String> lines : iter) {
Assert.assertTrue(lines.size() > 0); assertTrue(lines.size() > 0);
} }
} }
@ -26,6 +26,6 @@ public class PartitionIterTest {
for (List<Integer> lines : iter) { for (List<Integer> lines : iter) {
max = NumberUtil.max(max, NumberUtil.max(lines.toArray(new Integer[0]))); max = NumberUtil.max(max, NumberUtil.max(lines.toArray(new Integer[0])));
} }
Assert.assertEquals(45, max); assertEquals(45, max);
} }
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.core.collection; package cn.hutool.core.collection;
import cn.hutool.core.thread.ThreadUtil; import cn.hutool.core.thread.ThreadUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.List; import java.util.List;
@ -27,7 +27,7 @@ public class RingIndexUtilTest {
ThreadUtil.concurrencyTest(strList.size(), () -> { ThreadUtil.concurrencyTest(strList.size(), () -> {
final int index = RingIndexUtil.ringNextIntByObj(strList, atomicInteger); final int index = RingIndexUtil.ringNextIntByObj(strList, atomicInteger);
final String s = strList.get(index); final String s = strList.get(index);
Assert.assertNotNull(s); assertNotNull(s);
}); });
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.collection;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Set; import java.util.Set;
@ -18,7 +18,7 @@ public class UniqueKeySetTest {
set.add(new UniqueTestBean("id2", "王五", "木星")); set.add(new UniqueTestBean("id2", "王五", "木星"));
// 后两个ID重复 // 后两个ID重复
Assert.assertEquals(2, set.size()); assertEquals(2, set.size());
} }
@Data @Data

View File

@ -1,8 +1,8 @@
package cn.hutool.core.comparator; package cn.hutool.core.comparator;
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.collection.ListUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.List; import java.util.List;
@ -11,10 +11,10 @@ public class CompareUtilTest {
@Test @Test
public void compareTest(){ public void compareTest(){
int compare = CompareUtil.compare(null, "a", true); int compare = CompareUtil.compare(null, "a", true);
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
compare = CompareUtil.compare(null, "a", false); compare = CompareUtil.compare(null, "a", false);
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
} }
@Test @Test
@ -26,10 +26,10 @@ public class CompareUtilTest {
// 正序 // 正序
list.sort(CompareUtil.comparingPinyin(e -> e)); list.sort(CompareUtil.comparingPinyin(e -> e));
Assert.assertEquals(list, ascendingOrderResult); assertEquals(list, ascendingOrderResult);
// 反序 // 反序
list.sort(CompareUtil.comparingPinyin(e -> e, true)); list.sort(CompareUtil.comparingPinyin(e -> e, true));
Assert.assertEquals(list, descendingOrderResult); assertEquals(list, descendingOrderResult);
} }
} }

View File

@ -5,9 +5,9 @@ import cn.hutool.core.date.StopWatch;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.Arrays; import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
@ -23,10 +23,10 @@ public class IndexedComparatorTest {
final List<Object> sortSet = CollectionUtil.sort(set, new ArrayIndexedComparator<>(arr)); final List<Object> sortSet = CollectionUtil.sort(set, new ArrayIndexedComparator<>(arr));
Assert.assertEquals("a", sortSet.get(0)); assertEquals("a", sortSet.get(0));
Assert.assertEquals( new User("9", null), sortSet.get(2)); assertEquals( new User("9", null), sortSet.get(2));
Assert.assertEquals(3, sortSet.get(4)); assertEquals(3, sortSet.get(4));
Assert.assertNull(sortSet.get(5)); assertNull(sortSet.get(5));
} }
@Test @Test
@ -36,14 +36,14 @@ public class IndexedComparatorTest {
final List<Object> sortSet = CollectionUtil.sort(set, new ArrayIndexedComparator<>(arr).reversed()); final List<Object> sortSet = CollectionUtil.sort(set, new ArrayIndexedComparator<>(arr).reversed());
Assert.assertEquals("a", sortSet.get(6)); assertEquals("a", sortSet.get(6));
Assert.assertNull(sortSet.get(1)); assertNull(sortSet.get(1));
Assert.assertEquals( new User("9", null), sortSet.get(4)); assertEquals( new User("9", null), sortSet.get(4));
Assert.assertEquals(3, sortSet.get(2)); assertEquals(3, sortSet.get(2));
} }
@Test @Test
@Ignore @Disabled
public void benchmarkSortTest() { public void benchmarkSortTest() {
final Object[] arr ={"a", "b", new User("9", null), "1",3,null,"2"}; final Object[] arr ={"a", "b", new User("9", null), "1",3,null,"2"};
final Collection<Object> set = new HashSet<>(Arrays.asList(arr)); final Collection<Object> set = new HashSet<>(Arrays.asList(arr));

View File

@ -17,9 +17,9 @@ import cn.hutool.core.collection.ListUtil;
import cn.hutool.core.util.RandomUtil; import cn.hutool.core.util.RandomUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.ToString; import lombok.ToString;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -31,11 +31,11 @@ public class Issue3259Test {
Model x = new Model(1, 1); Model x = new Model(1, 1);
Model y = new Model(1, RandomUtil.randomInt(2, 100)); Model y = new Model(1, RandomUtil.randomInt(2, 100));
Assert.assertTrue(new FieldsComparator<>(Model.class, "a", "b").compare(x, y) < 0); assertTrue(new FieldsComparator<>(Model.class, "a", "b").compare(x, y) < 0);
} }
@Test @Test
@Ignore @Disabled
public void sortTest() { public void sortTest() {
for(int i = 2; i < 5; i++) { for(int i = 2; i < 5; i++) {
Model x = new Model(1, 1); Model x = new Model(1, 1);

View File

@ -3,8 +3,8 @@ package cn.hutool.core.comparator;
import cn.hutool.core.collection.ListUtil; import cn.hutool.core.collection.ListUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -20,15 +20,15 @@ public class PropertyComparatorTest {
// 默认null在末尾 // 默认null在末尾
final List<User> sortedList1 = ListUtil.sort(users, new PropertyComparator<>("b")); final List<User> sortedList1 = ListUtil.sort(users, new PropertyComparator<>("b"));
Assert.assertEquals("a", sortedList1.get(0).getB()); assertEquals("a", sortedList1.get(0).getB());
Assert.assertEquals("d", sortedList1.get(1).getB()); assertEquals("d", sortedList1.get(1).getB());
Assert.assertNull(sortedList1.get(2).getB()); assertNull(sortedList1.get(2).getB());
// null在首 // null在首
final List<User> sortedList2 = ListUtil.sort(users, new PropertyComparator<>("b", false)); final List<User> sortedList2 = ListUtil.sort(users, new PropertyComparator<>("b", false));
Assert.assertNull(sortedList2.get(0).getB()); assertNull(sortedList2.get(0).getB());
Assert.assertEquals("a", sortedList2.get(1).getB()); assertEquals("a", sortedList2.get(1).getB());
Assert.assertEquals("d", sortedList2.get(2).getB()); assertEquals("d", sortedList2.get(2).getB());
} }
@Test @Test
@ -41,9 +41,9 @@ public class PropertyComparatorTest {
// 反序 // 反序
final List<User> sortedList = ListUtil.sort(users, new PropertyComparator<>("b").reversed()); final List<User> sortedList = ListUtil.sort(users, new PropertyComparator<>("b").reversed());
Assert.assertNull(sortedList.get(0).getB()); assertNull(sortedList.get(0).getB());
Assert.assertEquals("d", sortedList.get(1).getB()); assertEquals("d", sortedList.get(1).getB());
Assert.assertEquals("a", sortedList.get(2).getB()); assertEquals("a", sortedList.get(2).getB());
} }
@Data @Data

View File

@ -1,7 +1,8 @@
package cn.hutool.core.comparator; package cn.hutool.core.comparator;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* 版本比较单元测试 * 版本比较单元测试
@ -13,110 +14,110 @@ public class VersionComparatorTest {
@Test @Test
public void compareEmptyTest() { public void compareEmptyTest() {
int compare = VersionComparator.INSTANCE.compare("", "1.12.1"); int compare = VersionComparator.INSTANCE.compare("", "1.12.1");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
compare = VersionComparator.INSTANCE.compare("", null); compare = VersionComparator.INSTANCE.compare("", null);
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
compare = VersionComparator.INSTANCE.compare(null, ""); compare = VersionComparator.INSTANCE.compare(null, "");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
} }
@Test @Test
public void versionComparatorTest1() { public void versionComparatorTest1() {
int compare = VersionComparator.INSTANCE.compare("1.2.1", "1.12.1"); int compare = VersionComparator.INSTANCE.compare("1.2.1", "1.12.1");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
// 自反测试 // 自反测试
compare = VersionComparator.INSTANCE.compare("1.12.1", "1.2.1"); compare = VersionComparator.INSTANCE.compare("1.12.1", "1.2.1");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
} }
@Test @Test
public void versionComparatorTest2() { public void versionComparatorTest2() {
int compare = VersionComparator.INSTANCE.compare("1.12.1", "1.12.1c"); int compare = VersionComparator.INSTANCE.compare("1.12.1", "1.12.1c");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.12.1"); compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.12.1");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
} }
@Test @Test
public void versionComparatorTest3() { public void versionComparatorTest3() {
int compare = VersionComparator.INSTANCE.compare(null, "1.12.1c"); int compare = VersionComparator.INSTANCE.compare(null, "1.12.1c");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
// 自反测试 // 自反测试
compare = VersionComparator.INSTANCE.compare("1.12.1c", null); compare = VersionComparator.INSTANCE.compare("1.12.1c", null);
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
} }
@Test @Test
public void versionComparatorTest4() { public void versionComparatorTest4() {
int compare = VersionComparator.INSTANCE.compare("1.13.0", "1.12.1c"); int compare = VersionComparator.INSTANCE.compare("1.13.0", "1.12.1c");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
// 自反测试 // 自反测试
compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.13.0"); compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.13.0");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
} }
@Test @Test
public void versionComparatorTest5() { public void versionComparatorTest5() {
int compare = VersionComparator.INSTANCE.compare("V1.2", "V1.1"); int compare = VersionComparator.INSTANCE.compare("V1.2", "V1.1");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
// 自反测试 // 自反测试
compare = VersionComparator.INSTANCE.compare("V1.1", "V1.2"); compare = VersionComparator.INSTANCE.compare("V1.1", "V1.2");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
} }
@Test @Test
public void versionComparatorTes6() { public void versionComparatorTes6() {
int compare = VersionComparator.INSTANCE.compare("V0.0.20170102", "V0.0.20170101"); int compare = VersionComparator.INSTANCE.compare("V0.0.20170102", "V0.0.20170101");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
// 自反测试 // 自反测试
compare = VersionComparator.INSTANCE.compare("V0.0.20170101", "V0.0.20170102"); compare = VersionComparator.INSTANCE.compare("V0.0.20170101", "V0.0.20170102");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
} }
@Test @Test
public void equalsTest() { public void equalsTest() {
VersionComparator first = new VersionComparator(); VersionComparator first = new VersionComparator();
VersionComparator other = new VersionComparator(); VersionComparator other = new VersionComparator();
Assert.assertNotEquals(first, other); assertNotEquals(first, other);
} }
@Test @Test
public void versionComparatorTest7() { public void versionComparatorTest7() {
int compare = VersionComparator.INSTANCE.compare("1.12.2", "1.12.1c"); int compare = VersionComparator.INSTANCE.compare("1.12.2", "1.12.1c");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
// 自反测试 // 自反测试
compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.12.2"); compare = VersionComparator.INSTANCE.compare("1.12.1c", "1.12.2");
Assert.assertTrue(compare < 0); assertTrue(compare < 0);
} }
@Test @Test
public void equalsTest2() { public void equalsTest2() {
final int compare = VersionComparator.INSTANCE.compare("1.12.0", "1.12"); final int compare = VersionComparator.INSTANCE.compare("1.12.0", "1.12");
Assert.assertEquals(0, compare); assertEquals(0, compare);
} }
@Test @Test
public void I8Z3VETest() { public void I8Z3VETest() {
// 传递性测试 // 传递性测试
int compare = VersionComparator.INSTANCE.compare("260", "a-34"); int compare = VersionComparator.INSTANCE.compare("260", "a-34");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
compare = VersionComparator.INSTANCE.compare("a-34", "a-3"); compare = VersionComparator.INSTANCE.compare("a-34", "a-3");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
compare = VersionComparator.INSTANCE.compare("260", "a-3"); compare = VersionComparator.INSTANCE.compare("260", "a-3");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
} }
@Test @Test
public void startWithNoneNumberTest() { public void startWithNoneNumberTest() {
final int compare = VersionComparator.INSTANCE.compare("V1", "A1"); final int compare = VersionComparator.INSTANCE.compare("V1", "A1");
Assert.assertTrue(compare > 0); assertTrue(compare > 0);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.comparator; package cn.hutool.core.comparator;
import cn.hutool.core.lang.Assert; import cn.hutool.core.lang.Assert;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.Collections; import java.util.Collections;

View File

@ -3,8 +3,8 @@ package cn.hutool.core.compiler;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ReflectUtil; import cn.hutool.core.util.ReflectUtil;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.io.InputStream; import java.io.InputStream;
@ -37,7 +37,7 @@ public class JavaSourceCompilerTest {
.compile(); .compile();
final Class<?> clazz = classLoader.loadClass("c.C"); final Class<?> clazz = classLoader.loadClass("c.C");
final Object obj = ReflectUtil.newInstance(clazz); final Object obj = ReflectUtil.newInstance(clazz);
Assert.assertTrue(String.valueOf(obj).startsWith("c.C@")); assertTrue(String.valueOf(obj).startsWith("c.C@"));
} }
@Test @Test
@ -50,7 +50,7 @@ public class JavaSourceCompilerTest {
} catch (final Exception ex) { } catch (final Exception ex) {
exception = ex; exception = ex;
} finally { } finally {
Assert.assertTrue(exception instanceof CompilerException); assertTrue(exception instanceof CompilerException);
} }
} }
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.core.compress; package cn.hutool.core.compress;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.nio.file.Paths; import java.nio.file.Paths;
import java.nio.file.StandardCopyOption; import java.nio.file.StandardCopyOption;
@ -10,7 +10,7 @@ import java.nio.file.StandardCopyOption;
public class IssueI5DRU0Test { public class IssueI5DRU0Test {
@Test @Test
@Ignore @Disabled
public void appendTest(){ public void appendTest(){
// https://gitee.com/dromara/hutool/issues/I5DRU0 // https://gitee.com/dromara/hutool/issues/I5DRU0
// 向zip中添加文件的时候如果添加的文件的父目录已经存在会报错实际中目录存在忽略即可 // 向zip中添加文件的时候如果添加的文件的父目录已经存在会报错实际中目录存在忽略即可

View File

@ -1,8 +1,8 @@
package cn.hutool.core.compress; package cn.hutool.core.compress;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
@ -11,7 +11,7 @@ import java.io.File;
*/ */
public class IssueIAGYDGTest { public class IssueIAGYDGTest {
@Test @Test
@Ignore @Disabled
public void zipTest() { public void zipTest() {
// 第一次压缩后IssueIAGYDG.zip也会作为文件压缩到IssueIAGYDG.zip中导致死循环 // 第一次压缩后IssueIAGYDG.zip也会作为文件压缩到IssueIAGYDG.zip中导致死循环
final File filea = new File("d:/test/"); final File filea = new File("d:/test/");

View File

@ -2,15 +2,15 @@ package cn.hutool.core.compress;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
public class ZipReaderTest { public class ZipReaderTest {
@Test @Test
@Ignore @Disabled
public void unzipTest() { public void unzipTest() {
File unzip = ZipUtil.unzip("d:/java.zip", "d:/test/java"); File unzip = ZipUtil.unzip("d:/java.zip", "d:/test/java");
Console.log(unzip); Console.log(unzip);

View File

@ -4,21 +4,21 @@ import cn.hutool.core.io.FileUtil;
import cn.hutool.core.io.resource.FileResource; import cn.hutool.core.io.resource.FileResource;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.ZipUtil; import cn.hutool.core.util.ZipUtil;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
public class ZipWriterTest { public class ZipWriterTest {
@Test @Test
@Ignore @Disabled
public void zipDirTest() { public void zipDirTest() {
ZipUtil.zip(new File("d:/test")); ZipUtil.zip(new File("d:/test"));
} }
@Test @Test
@Ignore @Disabled
public void addTest(){ public void addTest(){
final ZipWriter writer = ZipWriter.of(FileUtil.file("d:/test/test.zip"), CharsetUtil.CHARSET_UTF_8); final ZipWriter writer = ZipWriter.of(FileUtil.file("d:/test/test.zip"), CharsetUtil.CHARSET_UTF_8);
writer.add(new FileResource("d:/test/qr_c.png")); writer.add(new FileResource("d:/test/qr_c.png"));

View File

@ -1,8 +1,8 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.Serializable; import java.io.Serializable;
import java.util.Collection; import java.util.Collection;
@ -22,24 +22,24 @@ public class CastUtilTest {
map.put(1, 1); map.put(1, 1);
Collection<Number> collection2 = CastUtil.castUp(collection); Collection<Number> collection2 = CastUtil.castUp(collection);
Assert.assertSame(collection, collection2); assertSame(collection, collection2);
Collection<Integer> collection3 = CastUtil.castDown(collection2); Collection<Integer> collection3 = CastUtil.castDown(collection2);
Assert.assertSame(collection2, collection3); assertSame(collection2, collection3);
List<Number> list2 = CastUtil.castUp(list); List<Number> list2 = CastUtil.castUp(list);
Assert.assertSame(list, list2); assertSame(list, list2);
List<Integer> list3 = CastUtil.castDown(list2); List<Integer> list3 = CastUtil.castDown(list2);
Assert.assertSame(list2, list3); assertSame(list2, list3);
Set<Number> set2 = CastUtil.castUp(set); Set<Number> set2 = CastUtil.castUp(set);
Assert.assertSame(set, set2); assertSame(set, set2);
Set<Integer> set3 = CastUtil.castDown(set2); Set<Integer> set3 = CastUtil.castDown(set2);
Assert.assertSame(set2, set3); assertSame(set2, set3);
Map<Number, Serializable> map2 = CastUtil.castUp(map); Map<Number, Serializable> map2 = CastUtil.castUp(map);
Assert.assertSame(map, map2); assertSame(map, map2);
Map<Integer, Number> map3 = CastUtil.castDown(map2); Map<Integer, Number> map3 = CastUtil.castDown(map2);
Assert.assertSame(map2, map3); assertSame(map2, map3);
} }
} }

View File

@ -1,8 +1,8 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import cn.hutool.core.util.CharsetUtil; import cn.hutool.core.util.CharsetUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
@ -16,10 +16,10 @@ public class ConvertOtherTest {
public void hexTest() { public void hexTest() {
String a = "我是一个小小的可爱的字符串"; String a = "我是一个小小的可爱的字符串";
String hex = Convert.toHex(a, CharsetUtil.CHARSET_UTF_8); String hex = Convert.toHex(a, CharsetUtil.CHARSET_UTF_8);
Assert.assertEquals("e68891e698afe4b880e4b8aae5b08fe5b08fe79a84e58fafe788b1e79a84e5ad97e7aca6e4b8b2", hex); assertEquals("e68891e698afe4b880e4b8aae5b08fe5b08fe79a84e58fafe788b1e79a84e5ad97e7aca6e4b8b2", hex);
String raw = Convert.hexToStr(hex, CharsetUtil.CHARSET_UTF_8); String raw = Convert.hexToStr(hex, CharsetUtil.CHARSET_UTF_8);
Assert.assertEquals(a, raw); assertEquals(a, raw);
} }
@Test @Test
@ -27,18 +27,18 @@ public class ConvertOtherTest {
String a = "我是一个小小的可爱的字符串"; String a = "我是一个小小的可爱的字符串";
String unicode = Convert.strToUnicode(a); String unicode = Convert.strToUnicode(a);
Assert.assertEquals("\\u6211\\u662f\\u4e00\\u4e2a\\u5c0f\\u5c0f\\u7684\\u53ef\\u7231\\u7684\\u5b57\\u7b26\\u4e32", unicode); assertEquals("\\u6211\\u662f\\u4e00\\u4e2a\\u5c0f\\u5c0f\\u7684\\u53ef\\u7231\\u7684\\u5b57\\u7b26\\u4e32", unicode);
String raw = Convert.unicodeToStr(unicode); String raw = Convert.unicodeToStr(unicode);
Assert.assertEquals(raw, a); assertEquals(raw, a);
// 针对有特殊空白符的Unicode // 针对有特殊空白符的Unicode
String str = "你 好"; String str = "你 好";
String unicode2 = Convert.strToUnicode(str); String unicode2 = Convert.strToUnicode(str);
Assert.assertEquals("\\u4f60\\u00a0\\u597d", unicode2); assertEquals("\\u4f60\\u00a0\\u597d", unicode2);
String str2 = Convert.unicodeToStr(unicode2); String str2 = Convert.unicodeToStr(unicode2);
Assert.assertEquals(str, str2); assertEquals(str, str2);
} }
@Test @Test
@ -47,14 +47,14 @@ public class ConvertOtherTest {
// 转换后result为乱码 // 转换后result为乱码
String result = Convert.convertCharset(a, CharsetUtil.UTF_8, CharsetUtil.ISO_8859_1); String result = Convert.convertCharset(a, CharsetUtil.UTF_8, CharsetUtil.ISO_8859_1);
String raw = Convert.convertCharset(result, CharsetUtil.ISO_8859_1, "UTF-8"); String raw = Convert.convertCharset(result, CharsetUtil.ISO_8859_1, "UTF-8");
Assert.assertEquals(raw, a); assertEquals(raw, a);
} }
@Test @Test
public void convertTimeTest() { public void convertTimeTest() {
long a = 4535345; long a = 4535345;
long minutes = Convert.convertTime(a, TimeUnit.MILLISECONDS, TimeUnit.MINUTES); long minutes = Convert.convertTime(a, TimeUnit.MILLISECONDS, TimeUnit.MINUTES);
Assert.assertEquals(75, minutes); assertEquals(75, minutes);
} }
@Test @Test
@ -62,11 +62,11 @@ public class ConvertOtherTest {
// 去包装 // 去包装
Class<?> wrapClass = Integer.class; Class<?> wrapClass = Integer.class;
Class<?> unWraped = Convert.unWrap(wrapClass); Class<?> unWraped = Convert.unWrap(wrapClass);
Assert.assertEquals(int.class, unWraped); assertEquals(int.class, unWraped);
// 包装 // 包装
Class<?> primitiveClass = long.class; Class<?> primitiveClass = long.class;
Class<?> wraped = Convert.wrap(primitiveClass); Class<?> wraped = Convert.wrap(primitiveClass);
Assert.assertEquals(Long.class, wraped); assertEquals(Long.class, wraped);
} }
} }

View File

@ -10,8 +10,7 @@ import cn.hutool.core.util.HexUtil;
import lombok.AllArgsConstructor; import lombok.AllArgsConstructor;
import lombok.Data; import lombok.Data;
import lombok.Getter; import lombok.Getter;
import org.junit.Assert; import org.junit.jupiter.api.Test;
import org.junit.Test;
import java.io.Serializable; import java.io.Serializable;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -22,152 +21,152 @@ import java.util.concurrent.atomic.AtomicIntegerArray;
import java.util.concurrent.atomic.AtomicLongArray; import java.util.concurrent.atomic.AtomicLongArray;
import java.util.concurrent.atomic.DoubleAdder; import java.util.concurrent.atomic.DoubleAdder;
import static org.junit.jupiter.api.Assertions.*;
/** /**
* 类型转换工具单元测试 * 类型转换工具单元测试
* *
* @author Looly * @author Looly
*
*/ */
public class ConvertTest { public class ConvertTest {
@Test @Test
public void toObjectTest() { public void toObjectTest() {
final Object result = Convert.convert(Object.class, "aaaa"); final Object result = Convert.convert(Object.class, "aaaa");
Assert.assertEquals("aaaa", result); assertEquals("aaaa", result);
} }
@Test @Test
public void toStrTest() { public void toStrTest() {
final int a = 1; final int a = 1;
final long[] b = { 1, 2, 3, 4, 5 }; final long[] b = {1, 2, 3, 4, 5};
Assert.assertEquals("[1, 2, 3, 4, 5]", Convert.convert(String.class, b)); assertEquals("[1, 2, 3, 4, 5]", Convert.convert(String.class, b));
final String aStr = Convert.toStr(a); final String aStr = Convert.toStr(a);
Assert.assertEquals("1", aStr); assertEquals("1", aStr);
final String bStr = Convert.toStr(b); final String bStr = Convert.toStr(b);
Assert.assertEquals("[1, 2, 3, 4, 5]", Convert.toStr(bStr)); assertEquals("[1, 2, 3, 4, 5]", Convert.toStr(bStr));
} }
@Test @Test
public void toStrTest2() { public void toStrTest2() {
final String result = Convert.convert(String.class, "aaaa"); final String result = Convert.convert(String.class, "aaaa");
Assert.assertEquals("aaaa", result); assertEquals("aaaa", result);
} }
@Test @Test
public void toStrTest3() { public void toStrTest3() {
final char a = 'a'; final char a = 'a';
final String result = Convert.convert(String.class, a); final String result = Convert.convert(String.class, a);
Assert.assertEquals("a", result); assertEquals("a", result);
} }
@Test @Test
public void toStrTest4() { public void toStrTest4() {
// 被当作八进制 // 被当作八进制
@SuppressWarnings("OctalInteger") @SuppressWarnings("OctalInteger") final String result = Convert.toStr(001200);
final String result = Convert.toStr(001200); assertEquals("640", result);
Assert.assertEquals("640", result);
} }
@Test @Test
public void toIntTest() { public void toIntTest() {
final String a = " 34232"; final String a = " 34232";
final Integer aInteger = Convert.toInt(a); final Integer aInteger = Convert.toInt(a);
Assert.assertEquals(Integer.valueOf(34232), aInteger); assertEquals(Integer.valueOf(34232), aInteger);
final int aInt = ConverterRegistry.getInstance().convert(int.class, a); final int aInt = ConverterRegistry.getInstance().convert(int.class, a);
Assert.assertEquals(34232, aInt); assertEquals(34232, aInt);
// 带小数测试 // 带小数测试
final String b = " 34232.00"; final String b = " 34232.00";
final Integer bInteger = Convert.toInt(b); final Integer bInteger = Convert.toInt(b);
Assert.assertEquals(Integer.valueOf(34232), bInteger); assertEquals(Integer.valueOf(34232), bInteger);
final int bInt = ConverterRegistry.getInstance().convert(int.class, b); final int bInt = ConverterRegistry.getInstance().convert(int.class, b);
Assert.assertEquals(34232, bInt); assertEquals(34232, bInt);
// boolean测试 // boolean测试
final boolean c = true; final boolean c = true;
final Integer cInteger = Convert.toInt(c); final Integer cInteger = Convert.toInt(c);
Assert.assertEquals(Integer.valueOf(1), cInteger); assertEquals(Integer.valueOf(1), cInteger);
final int cInt = ConverterRegistry.getInstance().convert(int.class, c); final int cInt = ConverterRegistry.getInstance().convert(int.class, c);
Assert.assertEquals(1, cInt); assertEquals(1, cInt);
// boolean测试 // boolean测试
final String d = "08"; final String d = "08";
final Integer dInteger = Convert.toInt(d); final Integer dInteger = Convert.toInt(d);
Assert.assertEquals(Integer.valueOf(8), dInteger); assertEquals(Integer.valueOf(8), dInteger);
final int dInt = ConverterRegistry.getInstance().convert(int.class, d); final int dInt = ConverterRegistry.getInstance().convert(int.class, d);
Assert.assertEquals(8, dInt); assertEquals(8, dInt);
} }
@Test @Test
public void toIntTest2() { public void toIntTest2() {
final ArrayList<String> array = new ArrayList<>(); final ArrayList<String> array = new ArrayList<>();
final Integer aInt = Convert.convertQuietly(Integer.class, array, -1); final Integer aInt = Convert.convertQuietly(Integer.class, array, -1);
Assert.assertEquals(Integer.valueOf(-1), aInt); assertEquals(Integer.valueOf(-1), aInt);
} }
@Test @Test
public void toLongTest() { public void toLongTest() {
final String a = " 342324545435435"; final String a = " 342324545435435";
final Long aLong = Convert.toLong(a); final Long aLong = Convert.toLong(a);
Assert.assertEquals(Long.valueOf(342324545435435L), aLong); assertEquals(Long.valueOf(342324545435435L), aLong);
final long aLong2 = ConverterRegistry.getInstance().convert(long.class, a); final long aLong2 = ConverterRegistry.getInstance().convert(long.class, a);
Assert.assertEquals(342324545435435L, aLong2); assertEquals(342324545435435L, aLong2);
// 带小数测试 // 带小数测试
final String b = " 342324545435435.245435435"; final String b = " 342324545435435.245435435";
final Long bLong = Convert.toLong(b); final Long bLong = Convert.toLong(b);
Assert.assertEquals(Long.valueOf(342324545435435L), bLong); assertEquals(Long.valueOf(342324545435435L), bLong);
final long bLong2 = ConverterRegistry.getInstance().convert(long.class, b); final long bLong2 = ConverterRegistry.getInstance().convert(long.class, b);
Assert.assertEquals(342324545435435L, bLong2); assertEquals(342324545435435L, bLong2);
// boolean测试 // boolean测试
final boolean c = true; final boolean c = true;
final Long cLong = Convert.toLong(c); final Long cLong = Convert.toLong(c);
Assert.assertEquals(Long.valueOf(1), cLong); assertEquals(Long.valueOf(1), cLong);
final long cLong2 = ConverterRegistry.getInstance().convert(long.class, c); final long cLong2 = ConverterRegistry.getInstance().convert(long.class, c);
Assert.assertEquals(1, cLong2); assertEquals(1, cLong2);
// boolean测试 // boolean测试
final String d = "08"; final String d = "08";
final Long dLong = Convert.toLong(d); final Long dLong = Convert.toLong(d);
Assert.assertEquals(Long.valueOf(8), dLong); assertEquals(Long.valueOf(8), dLong);
final long dLong2 = ConverterRegistry.getInstance().convert(long.class, d); final long dLong2 = ConverterRegistry.getInstance().convert(long.class, d);
Assert.assertEquals(8, dLong2); assertEquals(8, dLong2);
} }
@Test @Test
public void toLongFromNumberWithFormatTest() { public void toLongFromNumberWithFormatTest() {
final NumberWithFormat value = new NumberWithFormat(1678285713935L, null); final NumberWithFormat value = new NumberWithFormat(1678285713935L, null);
final Long aLong = Convert.convertWithCheck(Long.class, value, null, false); final Long aLong = Convert.convertWithCheck(Long.class, value, null, false);
Assert.assertEquals(new Long(1678285713935L), aLong); assertEquals(new Long(1678285713935L), aLong);
} }
@Test @Test
public void toCharTest() { public void toCharTest() {
final String str = "aadfdsfs"; final String str = "aadfdsfs";
final Character c = Convert.toChar(str); final Character c = Convert.toChar(str);
Assert.assertEquals(Character.valueOf('a'), c); assertEquals(Character.valueOf('a'), c);
// 转换失败 // 转换失败
final Object str2 = ""; final Object str2 = "";
final Character c2 = Convert.toChar(str2); final Character c2 = Convert.toChar(str2);
Assert.assertNull(c2); assertNull(c2);
} }
@Test @Test
public void toNumberTest() { public void toNumberTest() {
final Object a = "12.45"; final Object a = "12.45";
final Number number = Convert.toNumber(a); final Number number = Convert.toNumber(a);
Assert.assertEquals(12.45D, number.doubleValue(), 0); assertEquals(12.45D, number.doubleValue(), 0);
} }
@Test @Test
public void emptyToNumberTest() { public void emptyToNumberTest() {
final Object a = ""; final Object a = "";
final Number number = Convert.toNumber(a); final Number number = Convert.toNumber(a);
Assert.assertNull(number); assertNull(number);
} }
@Test @Test
@ -175,10 +174,10 @@ public class ConvertTest {
// 测试 int byte // 测试 int byte
final int int0 = 234; final int int0 = 234;
final byte byte0 = Convert.intToByte(int0); final byte byte0 = Convert.intToByte(int0);
Assert.assertEquals(-22, byte0); assertEquals(-22, byte0);
final int int1 = Convert.byteToUnsignedInt(byte0); final int int1 = Convert.byteToUnsignedInt(byte0);
Assert.assertEquals(int0, int1); assertEquals(int0, int1);
} }
@Test @Test
@ -189,7 +188,7 @@ public class ConvertTest {
// 测试 byte 数组转 int // 测试 byte 数组转 int
final int int3 = Convert.bytesToInt(bytesInt); final int int3 = Convert.bytesToInt(bytesInt);
Assert.assertEquals(int2, int3); assertEquals(int2, int3);
} }
@Test @Test
@ -200,7 +199,7 @@ public class ConvertTest {
final byte[] bytesLong = Convert.longToBytes(long1); final byte[] bytesLong = Convert.longToBytes(long1);
final long long2 = Convert.bytesToLong(bytesLong); final long long2 = Convert.bytesToLong(bytesLong);
Assert.assertEquals(long1, long2); assertEquals(long1, long2);
} }
@Test @Test
@ -209,7 +208,7 @@ public class ConvertTest {
final byte[] bytes = Convert.shortToBytes(short1); final byte[] bytes = Convert.shortToBytes(short1);
final short short2 = Convert.bytesToShort(bytes); final short short2 = Convert.bytesToShort(bytes);
Assert.assertEquals(short2, short1); assertEquals(short2, short1);
} }
@Test @Test
@ -217,63 +216,63 @@ public class ConvertTest {
final List<String> list = Arrays.asList("1", "2"); final List<String> list = Arrays.asList("1", "2");
final String str = Convert.toStr(list); final String str = Convert.toStr(list);
final List<String> list2 = Convert.toList(String.class, str); final List<String> list2 = Convert.toList(String.class, str);
Assert.assertEquals("1", list2.get(0)); assertEquals("1", list2.get(0));
Assert.assertEquals("2", list2.get(1)); assertEquals("2", list2.get(1));
final List<Integer> list3 = Convert.toList(Integer.class, str); final List<Integer> list3 = Convert.toList(Integer.class, str);
Assert.assertEquals(1, list3.get(0).intValue()); assertEquals(1, list3.get(0).intValue());
Assert.assertEquals(2, list3.get(1).intValue()); assertEquals(2, list3.get(1).intValue());
} }
@Test @Test
public void toListTest2(){ public void toListTest2() {
final String str = "1,2"; final String str = "1,2";
final List<String> list2 = Convert.toList(String.class, str); final List<String> list2 = Convert.toList(String.class, str);
Assert.assertEquals("1", list2.get(0)); assertEquals("1", list2.get(0));
Assert.assertEquals("2", list2.get(1)); assertEquals("2", list2.get(1));
final List<Integer> list3 = Convert.toList(Integer.class, str); final List<Integer> list3 = Convert.toList(Integer.class, str);
Assert.assertEquals(1, list3.get(0).intValue()); assertEquals(1, list3.get(0).intValue());
Assert.assertEquals(2, list3.get(1).intValue()); assertEquals(2, list3.get(1).intValue());
} }
@Test @Test
public void toByteArrayTest(){ public void toByteArrayTest() {
// 测试Serializable转换为bytes调用序列化转换 // 测试Serializable转换为bytes调用序列化转换
final byte[] bytes = Convert.toPrimitiveByteArray(new Product("zhangsan", "张三", "5.1.1")); final byte[] bytes = Convert.toPrimitiveByteArray(new Product("zhangsan", "张三", "5.1.1"));
Assert.assertNotNull(bytes); assertNotNull(bytes);
final Product product = Convert.convert(Product.class, bytes); final Product product = Convert.convert(Product.class, bytes);
Assert.assertEquals("zhangsan", product.getName()); assertEquals("zhangsan", product.getName());
Assert.assertEquals("张三", product.getCName()); assertEquals("张三", product.getCName());
Assert.assertEquals("5.1.1", product.getVersion()); assertEquals("5.1.1", product.getVersion());
} }
@Test @Test
public void numberToByteArrayTest(){ public void numberToByteArrayTest() {
// 测试Serializable转换为bytes调用序列化转换 // 测试Serializable转换为bytes调用序列化转换
final byte[] bytes = Convert.toPrimitiveByteArray(12L); final byte[] bytes = Convert.toPrimitiveByteArray(12L);
Assert.assertArrayEquals(ByteUtil.longToBytes(12L), bytes); assertArrayEquals(ByteUtil.longToBytes(12L), bytes);
} }
@Test @Test
public void toAtomicIntegerArrayTest(){ public void toAtomicIntegerArrayTest() {
final String str = "1,2"; final String str = "1,2";
final AtomicIntegerArray atomicIntegerArray = Convert.convert(AtomicIntegerArray.class, str); final AtomicIntegerArray atomicIntegerArray = Convert.convert(AtomicIntegerArray.class, str);
Assert.assertEquals("[1, 2]", atomicIntegerArray.toString()); assertEquals("[1, 2]", atomicIntegerArray.toString());
} }
@Test @Test
public void toAtomicLongArrayTest(){ public void toAtomicLongArrayTest() {
final String str = "1,2"; final String str = "1,2";
final AtomicLongArray atomicLongArray = Convert.convert(AtomicLongArray.class, str); final AtomicLongArray atomicLongArray = Convert.convert(AtomicLongArray.class, str);
Assert.assertEquals("[1, 2]", atomicLongArray.toString()); assertEquals("[1, 2]", atomicLongArray.toString());
} }
@Test @Test
public void toClassTest(){ public void toClassTest() {
final Class<?> convert = Convert.convert(Class.class, "cn.hutool.core.convert.ConvertTest.Product"); final Class<?> convert = Convert.convert(Class.class, "cn.hutool.core.convert.ConvertTest.Product");
Assert.assertSame(Product.class, convert); assertSame(Product.class, convert);
} }
@Data @Data
@ -287,16 +286,16 @@ public class ConvertTest {
} }
@Test @Test
public void enumToIntTest(){ public void enumToIntTest() {
final Integer integer = Convert.toInt(BuildingType.CUO); final Integer integer = Convert.toInt(BuildingType.CUO);
Assert.assertEquals(1, integer.intValue()); assertEquals(1, integer.intValue());
} }
@Test @Test
public void toSetTest(){ public void toSetTest() {
final Set<Integer> result = Convert.convert(new TypeReference<Set<Integer>>() { final Set<Integer> result = Convert.convert(new TypeReference<Set<Integer>>() {
}, "1,2,3"); }, "1,2,3");
Assert.assertEquals(CollUtil.set(false, 1,2,3), result); assertEquals(CollUtil.set(false, 1, 2, 3), result);
} }
@Getter @Getter
@ -311,103 +310,104 @@ public class ConvertTest {
private final int id; private final int id;
private final String name; private final String name;
BuildingType(final int id, final String name){ BuildingType(final int id, final String name) {
this.id = id; this.id = id;
this.name = name; this.name = name;
} }
} }
@Test(expected = DateException.class) @Test
public void toDateTest(){ public void toDateTest() {
// 默认转换失败报错而不是返回null assertThrows(DateException.class, () -> {
Convert.convert(Date.class, "aaaa"); // 默认转换失败报错而不是返回null
Convert.convert(Date.class, "aaaa");
});
} }
@Test @Test
public void toDateTest2(){ public void toDateTest2() {
final Date date = Convert.toDate("2021-01"); final Date date = Convert.toDate("2021-01");
Assert.assertNull(date); assertNull(date);
} }
@Test @Test
public void toSqlDateTest(){ public void toSqlDateTest() {
final java.sql.Date date = Convert.convert(java.sql.Date.class, DateUtil.parse("2021-07-28")); final java.sql.Date date = Convert.convert(java.sql.Date.class, DateUtil.parse("2021-07-28"));
Assert.assertEquals("2021-07-28", date.toString()); assertEquals("2021-07-28", date.toString());
} }
@Test @Test
public void toHashtableTest(){ public void toHashtableTest() {
final Map<String, String> map = MapUtil.newHashMap(); final Map<String, String> map = MapUtil.newHashMap();
map.put("a1", "v1"); map.put("a1", "v1");
map.put("a2", "v2"); map.put("a2", "v2");
map.put("a3", "v3"); map.put("a3", "v3");
@SuppressWarnings("unchecked") @SuppressWarnings("unchecked") final Hashtable<String, String> hashtable = Convert.convert(Hashtable.class, map);
final Hashtable<String, String> hashtable = Convert.convert(Hashtable.class, map); assertEquals("v1", hashtable.get("a1"));
Assert.assertEquals("v1", hashtable.get("a1")); assertEquals("v2", hashtable.get("a2"));
Assert.assertEquals("v2", hashtable.get("a2")); assertEquals("v3", hashtable.get("a3"));
Assert.assertEquals("v3", hashtable.get("a3"));
} }
@Test @Test
public void toBigDecimalTest(){ public void toBigDecimalTest() {
// https://github.com/dromara/hutool/issues/1818 // https://github.com/dromara/hutool/issues/1818
final String str = "33020000210909112800000124"; final String str = "33020000210909112800000124";
final BigDecimal bigDecimal = Convert.toBigDecimal(str); final BigDecimal bigDecimal = Convert.toBigDecimal(str);
Assert.assertEquals(str, bigDecimal.toPlainString()); assertEquals(str, bigDecimal.toPlainString());
} }
@Test @Test
public void toFloatTest(){ public void toFloatTest() {
// https://gitee.com/dromara/hutool/issues/I4M0E4 // https://gitee.com/dromara/hutool/issues/I4M0E4
final String hex2 = "CD0CCB43"; final String hex2 = "CD0CCB43";
final byte[] value = HexUtil.decodeHex(hex2); final byte[] value = HexUtil.decodeHex(hex2);
final float f = Convert.toFloat(value); final float f = Convert.toFloat(value);
Assert.assertEquals(406.1F, f, 0); assertEquals(406.1F, f, 0);
} }
@Test @Test
public void floatToDoubleTest(){ public void floatToDoubleTest() {
final float a = 0.45f; final float a = 0.45f;
final double b = Convert.toDouble(a); final double b = Convert.toDouble(a);
Assert.assertEquals(0.45D, b, 0); assertEquals(0.45D, b, 0);
} }
@Test @Test
public void floatToDoubleAddrTest(){ public void floatToDoubleAddrTest() {
final float a = 0.45f; final float a = 0.45f;
final DoubleAdder adder = Convert.convert(DoubleAdder.class, a); final DoubleAdder adder = Convert.convert(DoubleAdder.class, a);
Assert.assertEquals(0.45D, adder.doubleValue(), 0); assertEquals(0.45D, adder.doubleValue(), 0);
} }
@Test @Test
public void doubleToFloatTest(){ public void doubleToFloatTest() {
final double a = 0.45f; final double a = 0.45f;
final float b = Convert.toFloat(a); final float b = Convert.toFloat(a);
Assert.assertEquals(a, b, 0); assertEquals(a, b, 0);
} }
@Test @Test
public void localDateTimeToLocalDateTest(){ public void localDateTimeToLocalDateTest() {
final LocalDateTime localDateTime = LocalDateTime.now(); final LocalDateTime localDateTime = LocalDateTime.now();
final LocalDate convert = Convert.convert(LocalDate.class, localDateTime); final LocalDate convert = Convert.convert(LocalDate.class, localDateTime);
Assert.assertEquals(localDateTime.toLocalDate(), convert); assertEquals(localDateTime.toLocalDate(), convert);
} }
@Test @Test
public void toSBCTest(){ public void toSBCTest() {
final String s = Convert.toSBC(null); final String s = Convert.toSBC(null);
Assert.assertNull(s); assertNull(s);
} }
@Test @Test
public void toDBCTest(){ public void toDBCTest() {
final String s = Convert.toDBC(null); final String s = Convert.toDBC(null);
Assert.assertNull(s); assertNull(s);
} }
@Test @Test
public void testChineseMoneyToNumber(){ public void testChineseMoneyToNumber() {
/* /*
* s=陆万柒仟伍佰伍拾陆圆, n=67556 * s=陆万柒仟伍佰伍拾陆圆, n=67556
* s=陆万柒仟伍佰伍拾陆元, n=67556 * s=陆万柒仟伍佰伍拾陆元, n=67556
@ -418,29 +418,31 @@ public class ConvertTest {
* s=叁角贰分, n=0.32 * s=叁角贰分, n=0.32
* s=陆万柒仟伍佰伍拾陆元叁角贰分, n=67556.32 * s=陆万柒仟伍佰伍拾陆元叁角贰分, n=67556.32
*/ */
Assert.assertEquals(67556, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆圆").longValue()); assertEquals(67556, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆圆").longValue());
Assert.assertEquals(67556, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元").longValue()); assertEquals(67556, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元").longValue());
Assert.assertEquals(0.3D, Convert.chineseMoneyToNumber("叁角").doubleValue(), 0); assertEquals(0.3D, Convert.chineseMoneyToNumber("叁角").doubleValue(), 0);
Assert.assertEquals(0.02, Convert.chineseMoneyToNumber("贰分").doubleValue(), 0); assertEquals(0.02, Convert.chineseMoneyToNumber("贰分").doubleValue(), 0);
Assert.assertEquals(67556.3, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元叁角").doubleValue(), 0); assertEquals(67556.3, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元叁角").doubleValue(), 0);
Assert.assertEquals(67556.02, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元贰分").doubleValue(), 0); assertEquals(67556.02, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元贰分").doubleValue(), 0);
Assert.assertEquals(0.32, Convert.chineseMoneyToNumber("叁角贰分").doubleValue(), 0); assertEquals(0.32, Convert.chineseMoneyToNumber("叁角贰分").doubleValue(), 0);
Assert.assertEquals(67556.32, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元叁角贰分").doubleValue(), 0); assertEquals(67556.32, Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾陆元叁角贰分").doubleValue(), 0);
} }
@Test(expected = IllegalArgumentException.class) @Test
public void convertQuietlyTest(){ public void convertQuietlyTest() {
final String a = "12"; assertThrows(Exception.class, () -> {
final Object s = Convert.convert(int.class, a, a); final String a = "12";
Assert.assertEquals(12, s); final Object s = Convert.convert(int.class, a, a);
assertEquals(12, s);
});
} }
@Test @Test
public void issue3662Test() { public void issue3662Test() {
String s = Convert.digitToChinese(0); String s = Convert.digitToChinese(0);
Assert.assertEquals("零元整", s); assertEquals("零元整", s);
s = Convert.digitToChinese(null); s = Convert.digitToChinese(null);
Assert.assertEquals("零元整", s); assertEquals("零元整", s);
} }
} }

View File

@ -3,9 +3,9 @@ package cn.hutool.core.convert;
import cn.hutool.core.convert.impl.ArrayConverter; import cn.hutool.core.convert.impl.ArrayConverter;
import cn.hutool.core.io.FileUtil; import cn.hutool.core.io.FileUtil;
import cn.hutool.core.lang.Console; import cn.hutool.core.lang.Console;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Ignore; import org.junit.jupiter.api.Disabled;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.io.File; import java.io.File;
import java.net.URL; import java.net.URL;
@ -25,14 +25,14 @@ public class ConvertToArrayTest {
String[] b = { "1", "2", "3", "4" }; String[] b = { "1", "2", "3", "4" };
Integer[] integerArray = Convert.toIntArray(b); Integer[] integerArray = Convert.toIntArray(b);
Assert.assertArrayEquals(integerArray, new Integer[]{1,2,3,4}); assertArrayEquals(integerArray, new Integer[]{1,2,3,4});
int[] intArray = Convert.convert(int[].class, b); int[] intArray = Convert.convert(int[].class, b);
Assert.assertArrayEquals(intArray, new int[]{1,2,3,4}); assertArrayEquals(intArray, new int[]{1,2,3,4});
long[] c = {1,2,3,4,5}; long[] c = {1,2,3,4,5};
Integer[] intArray2 = Convert.toIntArray(c); Integer[] intArray2 = Convert.toIntArray(c);
Assert.assertArrayEquals(intArray2, new Integer[]{1,2,3,4,5}); assertArrayEquals(intArray2, new Integer[]{1,2,3,4,5});
} }
@Test @Test
@ -41,7 +41,7 @@ public class ConvertToArrayTest {
final ArrayConverter arrayConverter = new ArrayConverter(Integer[].class, true); final ArrayConverter arrayConverter = new ArrayConverter(Integer[].class, true);
Integer[] integerArray = (Integer[]) arrayConverter.convert(b, null); Integer[] integerArray = (Integer[]) arrayConverter.convert(b, null);
Assert.assertArrayEquals(integerArray, new Integer[]{null, 1}); assertArrayEquals(integerArray, new Integer[]{null, 1});
} }
@Test @Test
@ -49,14 +49,14 @@ public class ConvertToArrayTest {
String[] b = { "1", "2", "3", "4" }; String[] b = { "1", "2", "3", "4" };
Long[] longArray = Convert.toLongArray(b); Long[] longArray = Convert.toLongArray(b);
Assert.assertArrayEquals(longArray, new Long[]{1L,2L,3L,4L}); assertArrayEquals(longArray, new Long[]{1L,2L,3L,4L});
long[] longArray2 = Convert.convert(long[].class, b); long[] longArray2 = Convert.convert(long[].class, b);
Assert.assertArrayEquals(longArray2, new long[]{1L,2L,3L,4L}); assertArrayEquals(longArray2, new long[]{1L,2L,3L,4L});
int[] c = {1,2,3,4,5}; int[] c = {1,2,3,4,5};
Long[] intArray2 = Convert.toLongArray(c); Long[] intArray2 = Convert.toLongArray(c);
Assert.assertArrayEquals(intArray2, new Long[]{1L,2L,3L,4L,5L}); assertArrayEquals(intArray2, new Long[]{1L,2L,3L,4L,5L});
} }
@Test @Test
@ -64,14 +64,14 @@ public class ConvertToArrayTest {
String[] b = { "1", "2", "3", "4" }; String[] b = { "1", "2", "3", "4" };
Double[] doubleArray = Convert.toDoubleArray(b); Double[] doubleArray = Convert.toDoubleArray(b);
Assert.assertArrayEquals(doubleArray, new Double[]{1D,2D,3D,4D}); assertArrayEquals(doubleArray, new Double[]{1D,2D,3D,4D});
double[] doubleArray2 = Convert.convert(double[].class, b); double[] doubleArray2 = Convert.convert(double[].class, b);
Assert.assertArrayEquals(doubleArray2, new double[]{1D,2D,3D,4D}, 2); assertArrayEquals(doubleArray2, new double[]{1D,2D,3D,4D}, 2);
int[] c = {1,2,3,4,5}; int[] c = {1,2,3,4,5};
Double[] intArray2 = Convert.toDoubleArray(c); Double[] intArray2 = Convert.toDoubleArray(c);
Assert.assertArrayEquals(intArray2, new Double[]{1D,2D,3D,4D,5D}); assertArrayEquals(intArray2, new Double[]{1D,2D,3D,4D,5D});
} }
@Test @Test
@ -80,18 +80,18 @@ public class ConvertToArrayTest {
//数组转数组测试 //数组转数组测试
int[] a = new int[]{1,2,3,4}; int[] a = new int[]{1,2,3,4};
long[] result = ConverterRegistry.getInstance().convert(long[].class, a); long[] result = ConverterRegistry.getInstance().convert(long[].class, a);
Assert.assertArrayEquals(new long[]{1L, 2L, 3L, 4L}, result); assertArrayEquals(new long[]{1L, 2L, 3L, 4L}, result);
//数组转数组测试 //数组转数组测试
byte[] resultBytes = ConverterRegistry.getInstance().convert(byte[].class, a); byte[] resultBytes = ConverterRegistry.getInstance().convert(byte[].class, a);
Assert.assertArrayEquals(new byte[]{1, 2, 3, 4}, resultBytes); assertArrayEquals(new byte[]{1, 2, 3, 4}, resultBytes);
//字符串转数组 //字符串转数组
String arrayStr = "1,2,3,4,5"; String arrayStr = "1,2,3,4,5";
//获取Converter类的方法2自己实例化相应Converter对象 //获取Converter类的方法2自己实例化相应Converter对象
ArrayConverter c3 = new ArrayConverter(int[].class); ArrayConverter c3 = new ArrayConverter(int[].class);
int[] result3 = (int[]) c3.convert(arrayStr, null); int[] result3 = (int[]) c3.convert(arrayStr, null);
Assert.assertArrayEquals(new int[]{1,2,3,4,5}, result3); assertArrayEquals(new int[]{1,2,3,4,5}, result3);
} }
@Test @Test
@ -102,9 +102,9 @@ public class ConvertToArrayTest {
list.add("c"); list.add("c");
String[] result = Convert.toStrArray(list); String[] result = Convert.toStrArray(list);
Assert.assertEquals(list.get(0), result[0]); assertEquals(list.get(0), result[0]);
Assert.assertEquals(list.get(1), result[1]); assertEquals(list.get(1), result[1]);
Assert.assertEquals(list.get(2), result[2]); assertEquals(list.get(2), result[2]);
} }
@Test @Test
@ -113,24 +113,24 @@ public class ConvertToArrayTest {
Character[] array = Convert.toCharArray(testStr); Character[] array = Convert.toCharArray(testStr);
//包装类型数组 //包装类型数组
Assert.assertEquals(new Character('a'), array[0]); assertEquals(new Character('a'), array[0]);
Assert.assertEquals(new Character('b'), array[1]); assertEquals(new Character('b'), array[1]);
Assert.assertEquals(new Character('c'), array[2]); assertEquals(new Character('c'), array[2]);
Assert.assertEquals(new Character('d'), array[3]); assertEquals(new Character('d'), array[3]);
Assert.assertEquals(new Character('e'), array[4]); assertEquals(new Character('e'), array[4]);
//原始类型数组 //原始类型数组
char[] array2 = Convert.convert(char[].class, testStr); char[] array2 = Convert.convert(char[].class, testStr);
Assert.assertEquals('a', array2[0]); assertEquals('a', array2[0]);
Assert.assertEquals('b', array2[1]); assertEquals('b', array2[1]);
Assert.assertEquals('c', array2[2]); assertEquals('c', array2[2]);
Assert.assertEquals('d', array2[3]); assertEquals('d', array2[3]);
Assert.assertEquals('e', array2[4]); assertEquals('e', array2[4]);
} }
@Test @Test
@Ignore @Disabled
public void toUrlArrayTest() { public void toUrlArrayTest() {
File[] files = FileUtil.file("D:\\workspace").listFiles(); File[] files = FileUtil.file("D:\\workspace").listFiles();

View File

@ -3,8 +3,8 @@ package cn.hutool.core.convert;
import cn.hutool.core.bean.BeanUtilTest.SubPerson; import cn.hutool.core.bean.BeanUtilTest.SubPerson;
import cn.hutool.core.lang.TypeReference; import cn.hutool.core.lang.TypeReference;
import cn.hutool.core.map.CaseInsensitiveMap; import cn.hutool.core.map.CaseInsensitiveMap;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.util.HashMap; import java.util.HashMap;
import java.util.LinkedHashMap; import java.util.LinkedHashMap;
@ -28,9 +28,9 @@ public class ConvertToBeanTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
Map<?, ?> map = Convert.convert(Map.class, person); Map<?, ?> map = Convert.convert(Map.class, person);
Assert.assertEquals(map.get("name"), "测试A11"); assertEquals(map.get("name"), "测试A11");
Assert.assertEquals(map.get("age"), 14); assertEquals(map.get("age"), 14);
Assert.assertEquals("11213232", map.get("openid")); assertEquals("11213232", map.get("openid"));
} }
@Test @Test
@ -42,15 +42,15 @@ public class ConvertToBeanTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
Map<String, String> map = Convert.toMap(String.class, String.class, person); Map<String, String> map = Convert.toMap(String.class, String.class, person);
Assert.assertEquals("测试A11", map.get("name")); assertEquals("测试A11", map.get("name"));
Assert.assertEquals("14", map.get("age")); assertEquals("14", map.get("age"));
Assert.assertEquals("11213232", map.get("openid")); assertEquals("11213232", map.get("openid"));
final LinkedHashMap<String, String> map2 = Convert.convert( final LinkedHashMap<String, String> map2 = Convert.convert(
new TypeReference<LinkedHashMap<String, String>>() {}, person); new TypeReference<LinkedHashMap<String, String>>() {}, person);
Assert.assertEquals("测试A11", map2.get("name")); assertEquals("测试A11", map2.get("name"));
Assert.assertEquals("14", map2.get("age")); assertEquals("14", map2.get("age"));
Assert.assertEquals("11213232", map2.get("openid")); assertEquals("11213232", map2.get("openid"));
} }
@Test @Test
@ -63,10 +63,10 @@ public class ConvertToBeanTest {
Map<String, String> map2 = Convert.toMap(String.class, String.class, map1); Map<String, String> map2 = Convert.toMap(String.class, String.class, map1);
Assert.assertEquals("1", map2.get("key1")); assertEquals("1", map2.get("key1"));
Assert.assertEquals("2", map2.get("key2")); assertEquals("2", map2.get("key2"));
Assert.assertEquals("3", map2.get("key3")); assertEquals("3", map2.get("key3"));
Assert.assertEquals("4", map2.get("key4")); assertEquals("4", map2.get("key4"));
} }
@Test @Test
public void mapToMapWithSelfTypeTest() { public void mapToMapWithSelfTypeTest() {
@ -76,9 +76,9 @@ public class ConvertToBeanTest {
caseInsensitiveMap.put("tom", 3); caseInsensitiveMap.put("tom", 3);
Map<String, String> map = Convert.toMap(String.class, String.class, caseInsensitiveMap); Map<String, String> map = Convert.toMap(String.class, String.class, caseInsensitiveMap);
Assert.assertEquals("2", map.get("jerry")); assertEquals("2", map.get("jerry"));
Assert.assertEquals("2", map.get("Jerry")); assertEquals("2", map.get("Jerry"));
Assert.assertEquals("3", map.get("tom")); assertEquals("3", map.get("tom"));
} }
@Test @Test
public void beanToSpecifyMapTest() { public void beanToSpecifyMapTest() {
@ -89,9 +89,9 @@ public class ConvertToBeanTest {
person.setSubName("sub名字"); person.setSubName("sub名字");
Map<String, String> map = Convert.toMap(LinkedHashMap.class, String.class, String.class, person); Map<String, String> map = Convert.toMap(LinkedHashMap.class, String.class, String.class, person);
Assert.assertEquals("测试A11", map.get("name")); assertEquals("测试A11", map.get("name"));
Assert.assertEquals("14", map.get("age")); assertEquals("14", map.get("age"));
Assert.assertEquals("11213232", map.get("openid")); assertEquals("11213232", map.get("openid"));
} }
@Test @Test
public void mapToBeanTest() { public void mapToBeanTest() {
@ -103,17 +103,17 @@ public class ConvertToBeanTest {
map.put("subName", "sub名字"); map.put("subName", "sub名字");
SubPerson subPerson = Convert.convert(SubPerson.class, map); SubPerson subPerson = Convert.convert(SubPerson.class, map);
Assert.assertEquals("88dc4b28-91b1-4a1a-bab5-444b795c7ecd", subPerson.getId().toString()); assertEquals("88dc4b28-91b1-4a1a-bab5-444b795c7ecd", subPerson.getId().toString());
Assert.assertEquals(14, subPerson.getAge()); assertEquals(14, subPerson.getAge());
Assert.assertEquals("11213232", subPerson.getOpenid()); assertEquals("11213232", subPerson.getOpenid());
Assert.assertEquals("测试A11", subPerson.getName()); assertEquals("测试A11", subPerson.getName());
Assert.assertEquals("11213232", subPerson.getOpenid()); assertEquals("11213232", subPerson.getOpenid());
} }
@Test @Test
public void nullStrToBeanTest(){ public void nullStrToBeanTest(){
String nullStr = "null"; String nullStr = "null";
final SubPerson subPerson = Convert.convertQuietly(SubPerson.class, nullStr); final SubPerson subPerson = Convert.convertQuietly(SubPerson.class, nullStr);
Assert.assertNull(subPerson); assertNull(subPerson);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
public class ConvertToBooleanTest { public class ConvertToBooleanTest {
@ -9,10 +9,10 @@ public class ConvertToBooleanTest {
public void intToBooleanTest(){ public void intToBooleanTest(){
int a = 100; int a = 100;
final Boolean aBoolean = Convert.toBool(a); final Boolean aBoolean = Convert.toBool(a);
Assert.assertTrue(aBoolean); assertTrue(aBoolean);
int b = 0; int b = 0;
final Boolean bBoolean = Convert.toBool(b); final Boolean bBoolean = Convert.toBool(b);
Assert.assertFalse(bBoolean); assertFalse(bBoolean);
} }
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.convert;
import cn.hutool.core.collection.CollUtil; import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.TypeReference; import cn.hutool.core.lang.TypeReference;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.ArrayList; import java.util.ArrayList;
@ -24,104 +24,104 @@ public class ConvertToCollectionTest {
public void toCollectionTest() { public void toCollectionTest() {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
List<?> list = (List<?>) Convert.convert(Collection.class, a); List<?> list = (List<?>) Convert.convert(Collection.class, a);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals(1, list.get(4)); assertEquals(1, list.get(4));
} }
@Test @Test
public void toListTest() { public void toListTest() {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
List<?> list = Convert.toList(a); List<?> list = Convert.toList(a);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals(1, list.get(4)); assertEquals(1, list.get(4));
} }
@Test @Test
public void toListTest2() { public void toListTest2() {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
List<String> list = Convert.toList(String.class, a); List<String> list = Convert.toList(String.class, a);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals("1", list.get(4)); assertEquals("1", list.get(4));
} }
@Test @Test
public void toListTest3() { public void toListTest3() {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
List<String> list = Convert.toList(String.class, a); List<String> list = Convert.toList(String.class, a);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals("1", list.get(4)); assertEquals("1", list.get(4));
} }
@Test @Test
public void toListTest4() { public void toListTest4() {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
List<String> list = Convert.convert(new TypeReference<List<String>>() {}, a); List<String> list = Convert.convert(new TypeReference<List<String>>() {}, a);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals("1", list.get(4)); assertEquals("1", list.get(4));
} }
@Test @Test
public void strToListTest() { public void strToListTest() {
String a = "a,你,好,123"; String a = "a,你,好,123";
List<?> list = Convert.toList(a); List<?> list = Convert.toList(a);
Assert.assertEquals(4, list.size()); assertEquals(4, list.size());
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("123", list.get(3)); assertEquals("123", list.get(3));
String b = "a"; String b = "a";
List<?> list2 = Convert.toList(b); List<?> list2 = Convert.toList(b);
Assert.assertEquals(1, list2.size()); assertEquals(1, list2.size());
Assert.assertEquals("a", list2.get(0)); assertEquals("a", list2.get(0));
} }
@Test @Test
public void strToListTest2() { public void strToListTest2() {
String a = "a,你,好,123"; String a = "a,你,好,123";
List<String> list = Convert.toList(String.class, a); List<String> list = Convert.toList(String.class, a);
Assert.assertEquals(4, list.size()); assertEquals(4, list.size());
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("123", list.get(3)); assertEquals("123", list.get(3));
} }
@Test @Test
public void numberToListTest() { public void numberToListTest() {
Integer i = 1; Integer i = 1;
ArrayList<?> list = Convert.convert(ArrayList.class, i); ArrayList<?> list = Convert.convert(ArrayList.class, i);
Assert.assertSame(i, list.get(0)); assertSame(i, list.get(0));
BigDecimal b = BigDecimal.ONE; BigDecimal b = BigDecimal.ONE;
ArrayList<?> list2 = Convert.convert(ArrayList.class, b); ArrayList<?> list2 = Convert.convert(ArrayList.class, b);
Assert.assertEquals(b, list2.get(0)); assertEquals(b, list2.get(0));
} }
@Test @Test
public void toLinkedListTest() { public void toLinkedListTest() {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
List<?> list = Convert.convert(LinkedList.class, a); List<?> list = Convert.convert(LinkedList.class, a);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals(1, list.get(4)); assertEquals(1, list.get(4));
} }
@Test @Test
@ -129,10 +129,10 @@ public class ConvertToCollectionTest {
Object[] a = { "a", "", "", "", 1 }; Object[] a = { "a", "", "", "", 1 };
LinkedHashSet<?> set = Convert.convert(LinkedHashSet.class, a); LinkedHashSet<?> set = Convert.convert(LinkedHashSet.class, a);
ArrayList<?> list = CollUtil.newArrayList(set); ArrayList<?> list = CollUtil.newArrayList(set);
Assert.assertEquals("a", list.get(0)); assertEquals("a", list.get(0));
Assert.assertEquals("", list.get(1)); assertEquals("", list.get(1));
Assert.assertEquals("", list.get(2)); assertEquals("", list.get(2));
Assert.assertEquals("", list.get(3)); assertEquals("", list.get(3));
Assert.assertEquals(1, list.get(4)); assertEquals(1, list.get(4));
} }
} }

View File

@ -2,8 +2,8 @@ package cn.hutool.core.convert;
import cn.hutool.core.date.DateTime; import cn.hutool.core.date.DateTime;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
import java.util.concurrent.atomic.AtomicLong; import java.util.concurrent.atomic.AtomicLong;
@ -14,7 +14,7 @@ public class ConvertToNumberTest {
final DateTime date = DateUtil.parse("2020-05-17 12:32:00"); final DateTime date = DateUtil.parse("2020-05-17 12:32:00");
final Long dateLong = Convert.toLong(date); final Long dateLong = Convert.toLong(date);
assert date != null; assert date != null;
Assert.assertEquals(date.getTime(), dateLong.longValue()); assertEquals(date.getTime(), dateLong.longValue());
} }
@Test @Test
@ -22,7 +22,7 @@ public class ConvertToNumberTest {
final DateTime date = DateUtil.parse("2020-05-17 12:32:00"); final DateTime date = DateUtil.parse("2020-05-17 12:32:00");
final Integer dateInt = Convert.toInt(date); final Integer dateInt = Convert.toInt(date);
assert date != null; assert date != null;
Assert.assertEquals((int)date.getTime(), dateInt.intValue()); assertEquals((int)date.getTime(), dateInt.intValue());
} }
@Test @Test
@ -30,15 +30,15 @@ public class ConvertToNumberTest {
final DateTime date = DateUtil.parse("2020-05-17 12:32:00"); final DateTime date = DateUtil.parse("2020-05-17 12:32:00");
final AtomicLong dateLong = Convert.convert(AtomicLong.class, date); final AtomicLong dateLong = Convert.convert(AtomicLong.class, date);
assert date != null; assert date != null;
Assert.assertEquals(date.getTime(), dateLong.longValue()); assertEquals(date.getTime(), dateLong.longValue());
} }
@Test @Test
public void toBigDecimalTest(){ public void toBigDecimalTest(){
BigDecimal bigDecimal = Convert.toBigDecimal("1.1f"); BigDecimal bigDecimal = Convert.toBigDecimal("1.1f");
Assert.assertEquals(1.1f, bigDecimal.floatValue(), 0); assertEquals(1.1f, bigDecimal.floatValue(), 0);
bigDecimal = Convert.toBigDecimal("1L"); bigDecimal = Convert.toBigDecimal("1L");
Assert.assertEquals(1L, bigDecimal.longValue()); assertEquals(1L, bigDecimal.longValue());
} }
} }

View File

@ -1,12 +1,12 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* 类型转换工具单元测试 * 类型转换工具单元测试
* 全角半角转换 * 全角半角转换
* *
* @author Looly * @author Looly
* *
*/ */
@ -16,13 +16,13 @@ public class ConvertToSBCAndDBCTest {
public void toSBCTest() { public void toSBCTest() {
String a = "123456789"; String a = "123456789";
String sbc = Convert.toSBC(a); String sbc = Convert.toSBC(a);
Assert.assertEquals("", sbc); assertEquals("", sbc);
} }
@Test @Test
public void toDBCTest() { public void toDBCTest() {
String a = ""; String a = "";
String dbc = Convert.toDBC(a); String dbc = Convert.toDBC(a);
Assert.assertEquals("123456789", dbc); assertEquals("123456789", dbc);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* ConverterRegistry 单元测试 * ConverterRegistry 单元测试
@ -9,28 +9,28 @@ import org.junit.Test;
* *
*/ */
public class ConverterRegistryTest { public class ConverterRegistryTest {
@Test @Test
public void getConverterTest() { public void getConverterTest() {
Converter<Object> converter = ConverterRegistry.getInstance().getConverter(CharSequence.class, false); Converter<Object> converter = ConverterRegistry.getInstance().getConverter(CharSequence.class, false);
Assert.assertNotNull(converter); assertNotNull(converter);
} }
@Test @Test
public void customTest(){ public void customTest(){
int a = 454553; int a = 454553;
ConverterRegistry converterRegistry = ConverterRegistry.getInstance(); ConverterRegistry converterRegistry = ConverterRegistry.getInstance();
CharSequence result = converterRegistry.convert(CharSequence.class, a); CharSequence result = converterRegistry.convert(CharSequence.class, a);
Assert.assertEquals("454553", result); assertEquals("454553", result);
//此处做为示例自定义CharSequence转换因为Hutool中已经提供CharSequence转换请尽量不要替换 //此处做为示例自定义CharSequence转换因为Hutool中已经提供CharSequence转换请尽量不要替换
//替换可能引发关联转换异常例如覆盖CharSequence转换会影响全局 //替换可能引发关联转换异常例如覆盖CharSequence转换会影响全局
converterRegistry.putCustom(CharSequence.class, CustomConverter.class); converterRegistry.putCustom(CharSequence.class, CustomConverter.class);
result = converterRegistry.convert(CharSequence.class, a); result = converterRegistry.convert(CharSequence.class, a);
Assert.assertEquals("Custom: 454553", result); assertEquals("Custom: 454553", result);
} }
public static class CustomConverter implements Converter<CharSequence>{ public static class CustomConverter implements Converter<CharSequence>{
@Override @Override
public CharSequence convert(Object value, CharSequence defaultValue) throws IllegalArgumentException { public CharSequence convert(Object value, CharSequence defaultValue) throws IllegalArgumentException {

View File

@ -1,8 +1,8 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import cn.hutool.core.date.DateUtil; import cn.hutool.core.date.DateUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.sql.Timestamp; import java.sql.Timestamp;
import java.time.LocalDateTime; import java.time.LocalDateTime;
@ -15,42 +15,42 @@ public class DateConvertTest {
public void toDateTest() { public void toDateTest() {
String a = "2017-05-06"; String a = "2017-05-06";
Date value = Convert.toDate(a); Date value = Convert.toDate(a);
Assert.assertEquals(a, DateUtil.formatDate(value)); assertEquals(a, DateUtil.formatDate(value));
long timeLong = DateUtil.date().getTime(); long timeLong = DateUtil.date().getTime();
Date value2 = Convert.toDate(timeLong); Date value2 = Convert.toDate(timeLong);
Assert.assertEquals(timeLong, value2.getTime()); assertEquals(timeLong, value2.getTime());
} }
@Test @Test
public void toDateFromIntTest() { public void toDateFromIntTest() {
int dateLong = -1497600000; int dateLong = -1497600000;
Date value = Convert.toDate(dateLong); Date value = Convert.toDate(dateLong);
Assert.assertNotNull(value); assertNotNull(value);
Assert.assertEquals("Mon Dec 15 00:00:00 CST 1969", value.toString().replace("GMT+08:00", "CST")); 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); final java.sql.Date sqlDate = Convert.convert(java.sql.Date.class, dateLong);
Assert.assertNotNull(sqlDate); assertNotNull(sqlDate);
Assert.assertEquals("1969-12-15", sqlDate.toString()); assertEquals("1969-12-15", sqlDate.toString());
} }
@Test @Test
public void toDateFromLocalDateTimeTest() { public void toDateFromLocalDateTimeTest() {
LocalDateTime localDateTime = LocalDateTime.parse("2017-05-06T08:30:00", DateTimeFormatter.ISO_DATE_TIME); LocalDateTime localDateTime = LocalDateTime.parse("2017-05-06T08:30:00", DateTimeFormatter.ISO_DATE_TIME);
Date value = Convert.toDate(localDateTime); Date value = Convert.toDate(localDateTime);
Assert.assertNotNull(value); assertNotNull(value);
Assert.assertEquals("2017-05-06", DateUtil.formatDate(value)); assertEquals("2017-05-06", DateUtil.formatDate(value));
} }
@Test @Test
public void toSqlDateTest() { public void toSqlDateTest() {
String a = "2017-05-06"; String a = "2017-05-06";
java.sql.Date value = Convert.convert(java.sql.Date.class, a); java.sql.Date value = Convert.convert(java.sql.Date.class, a);
Assert.assertEquals("2017-05-06", value.toString()); assertEquals("2017-05-06", value.toString());
long timeLong = DateUtil.date().getTime(); long timeLong = DateUtil.date().getTime();
java.sql.Date value2 = Convert.convert(java.sql.Date.class, timeLong); java.sql.Date value2 = Convert.convert(java.sql.Date.class, timeLong);
Assert.assertEquals(timeLong, value2.getTime()); assertEquals(timeLong, value2.getTime());
} }
@Test @Test
@ -58,14 +58,14 @@ public class DateConvertTest {
Date src = new Date(); Date src = new Date();
LocalDateTime ldt = Convert.toLocalDateTime(src); LocalDateTime ldt = Convert.toLocalDateTime(src);
Assert.assertEquals(ldt, DateUtil.toLocalDateTime(src)); assertEquals(ldt, DateUtil.toLocalDateTime(src));
Timestamp ts = Timestamp.from(src.toInstant()); Timestamp ts = Timestamp.from(src.toInstant());
ldt = Convert.toLocalDateTime(ts); ldt = Convert.toLocalDateTime(ts);
Assert.assertEquals(ldt, DateUtil.toLocalDateTime(src)); assertEquals(ldt, DateUtil.toLocalDateTime(src));
String str = "2020-12-12 12:12:12.0"; String str = "2020-12-12 12:12:12.0";
ldt = Convert.toLocalDateTime(str); ldt = Convert.toLocalDateTime(str);
Assert.assertEquals(ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")), str); assertEquals(ldt.format(DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss.S")), str);
} }
} }

View File

@ -1,7 +1,7 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
/** /**
* Enum转换单元测试 * Enum转换单元测试
@ -11,19 +11,19 @@ public class EnumConvertTest {
@Test @Test
public void convertTest(){ public void convertTest(){
TestEnum bbb = Convert.convert(TestEnum.class, "BBB"); TestEnum bbb = Convert.convert(TestEnum.class, "BBB");
Assert.assertEquals(TestEnum.B, bbb); assertEquals(TestEnum.B, bbb);
bbb = Convert.convert(TestEnum.class, 22); bbb = Convert.convert(TestEnum.class, 22);
Assert.assertEquals(TestEnum.B, bbb); assertEquals(TestEnum.B, bbb);
} }
@Test @Test
public void toEnumTest(){ public void toEnumTest(){
TestEnum ccc = Convert.toEnum(TestEnum.class, "CCC"); TestEnum ccc = Convert.toEnum(TestEnum.class, "CCC");
Assert.assertEquals(TestEnum.C, ccc); assertEquals(TestEnum.C, ccc);
ccc = Convert.toEnum(TestEnum.class, 33); ccc = Convert.toEnum(TestEnum.class, 33);
Assert.assertEquals(TestEnum.C, ccc); assertEquals(TestEnum.C, ccc);
} }
enum TestEnum { enum TestEnum {

View File

@ -1,8 +1,8 @@
package cn.hutool.core.convert; package cn.hutool.core.convert;
import cn.hutool.core.util.NumberUtil; import cn.hutool.core.util.NumberUtil;
import org.junit.Assert; import static org.junit.jupiter.api.Assertions.*;
import org.junit.Test; import org.junit.jupiter.api.Test;
import java.math.BigDecimal; import java.math.BigDecimal;
@ -12,6 +12,6 @@ public class Issue2611Test {
public void chineseMoneyToNumberTest(){ public void chineseMoneyToNumberTest(){
final BigDecimal value = Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾柒元"); final BigDecimal value = Convert.chineseMoneyToNumber("陆万柒仟伍佰伍拾柒元");
Assert.assertEquals("67,557.00", NumberUtil.decimalFormatMoney(value.doubleValue())); assertEquals("67,557.00", NumberUtil.decimalFormatMoney(value.doubleValue()));
} }
} }

Some files were not shown because too many files have changed in this diff Show More