From a2b527e3b9dc88e31f2c180950faf37352d9c914 Mon Sep 17 00:00:00 2001 From: Natalie Boardway Date: Fri, 14 Jun 2019 13:37:01 -0400 Subject: [PATCH] Add explicit support for TimeSpan deserialization/ related tests --- src/JsonApiDotNetCore/Internal/TypeHelper.cs | 3 +++ test/UnitTests/Internal/TypeHelper_Tests.cs | 24 ++++++++++++++++++++ 2 files changed, 27 insertions(+) diff --git a/src/JsonApiDotNetCore/Internal/TypeHelper.cs b/src/JsonApiDotNetCore/Internal/TypeHelper.cs index 5d1842d350..75ae84d380 100644 --- a/src/JsonApiDotNetCore/Internal/TypeHelper.cs +++ b/src/JsonApiDotNetCore/Internal/TypeHelper.cs @@ -40,6 +40,9 @@ public static object ConvertType(object value, Type type) if (type == typeof(DateTimeOffset)) return DateTimeOffset.Parse(stringValue); + if(type == typeof(TimeSpan)) + return TimeSpan.Parse(stringValue); + if (type.GetTypeInfo().IsEnum) return Enum.Parse(type, stringValue); diff --git a/test/UnitTests/Internal/TypeHelper_Tests.cs b/test/UnitTests/Internal/TypeHelper_Tests.cs index 6fcaa68eb5..1c105659f5 100644 --- a/test/UnitTests/Internal/TypeHelper_Tests.cs +++ b/test/UnitTests/Internal/TypeHelper_Tests.cs @@ -106,6 +106,30 @@ public void ConvertType_Returns_Default_Value_For_Empty_Strings() Assert.Equal(t.Value, result); } } + + [Fact] + public void Can_Convert_TimeSpans() + { + //arrange + TimeSpan timeSpan = TimeSpan.FromMinutes(45); + string stringSpan = timeSpan.ToString(); + + //act + var result = TypeHelper.ConvertType(stringSpan, typeof(TimeSpan)); + + //assert + Assert.Equal(timeSpan, result); + } + + [Fact] + public void Bad_TimeSpanString_Throws() + { + // arrange + var formattedString = "this_is_not_a_valid_timespan"; + + // act/assert + Assert.Throws(() => TypeHelper.ConvertType(formattedString, typeof(TimeSpan))); + } private enum TestEnum {