From 9612432d61198962755d51bd520a564d0d4292f7 Mon Sep 17 00:00:00 2001 From: happycoder Date: Mon, 9 Jan 2023 21:12:30 +0800 Subject: [PATCH] =?UTF-8?q?=E6=8F=90=E4=BA=A4Convert.toStr(final=20Object?= =?UTF-8?q?=20value,=20final=20String=20defaultValue)=E7=9A=84=E6=B5=8B?= =?UTF-8?q?=E8=AF=95=E6=96=B9=E6=B3=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- .../cn/hutool/core/convert/ConvertTest.java | 32 +++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/hutool-core/src/test/java/cn/hutool/core/convert/ConvertTest.java b/hutool-core/src/test/java/cn/hutool/core/convert/ConvertTest.java index 52d75769b..3c6b9ff74 100755 --- a/hutool-core/src/test/java/cn/hutool/core/convert/ConvertTest.java +++ b/hutool-core/src/test/java/cn/hutool/core/convert/ConvertTest.java @@ -42,6 +42,17 @@ public class ConvertTest { Assert.assertEquals("aaaa", result); } + /** + * 调取对象的toString方法会抛异常的测试类 + */ + @Data + private static class TestExceptionClass { + @Override + public String toString() { + throw new RuntimeException(); + } + } + @Test public void toStrTest() { final int a = 1; @@ -76,6 +87,27 @@ public class ConvertTest { Assert.assertEquals("640", result); } + @Test + public void toStrTest5() { + // 被转化的对象有值,正常转换 + String a = "aaaa"; + String aDefaultValue = "aDefault"; + String aResult = Convert.toStr(a, aDefaultValue); + Assert.assertEquals(aResult, a); + + // 被转化的对象为null,返回默认值 + String b = null; + String bDefaultValue = "bDefault"; + String bResult = Convert.toStr(b, bDefaultValue); + Assert.assertEquals(bResult, bDefaultValue); + + // 转换失败,返回默认值 + TestExceptionClass c = new TestExceptionClass(); + String cDefaultValue = "cDefault"; + String cResult = Convert.toStr(c, cDefaultValue); + Assert.assertEquals(cResult, cDefaultValue); + } + @Test public void toIntTest() { final String a = " 34232";