Skip to content

Commit 3de6d21

Browse files
committed
fix(typeHelper): handle complex types
closes #137
1 parent 46f2d07 commit 3de6d21

File tree

2 files changed

+59
-4
lines changed

2 files changed

+59
-4
lines changed

src/JsonApiDotNetCore/Internal/TypeHelper.cs

Lines changed: 8 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,15 @@ public static class TypeHelper
77
{
88
public static object ConvertType(object value, Type type)
99
{
10+
if (value == null)
11+
return null;
12+
13+
var valueType = value.GetType();
14+
1015
try
1116
{
12-
if (value == null)
13-
return null;
17+
if (valueType == type || type.IsAssignableFrom(valueType))
18+
return value;
1419

1520
type = Nullable.GetUnderlyingType(type) ?? type;
1621

@@ -29,7 +34,7 @@ public static object ConvertType(object value, Type type)
2934
}
3035
catch (Exception e)
3136
{
32-
throw new FormatException($"{ value } cannot be converted to { type.GetTypeInfo().Name }", e);
37+
throw new FormatException($"{ valueType } cannot be converted to { type }", e);
3338
}
3439
}
3540

test/UnitTests/Internal/TypeHelper_Tests.cs

Lines changed: 51 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -44,9 +44,59 @@ public void Can_Convert_Enums()
4444
Assert.Equal(TestEnum.Test, result);
4545
}
4646

47-
public enum TestEnum
47+
[Fact]
48+
public void ConvertType_Returns_Value_If_Type_Is_Same()
49+
{
50+
// arrange
51+
var val = new ComplexType
52+
{
53+
Property = 1
54+
};
55+
56+
var type = val.GetType();
57+
58+
// act
59+
var result = TypeHelper.ConvertType(val, type);
60+
61+
// assert
62+
Assert.Equal(val, result);
63+
}
64+
65+
[Fact]
66+
public void ConvertType_Returns_Value_If_Type_Is_Assignable()
67+
{
68+
// arrange
69+
var val = new ComplexType
70+
{
71+
Property = 1
72+
};
73+
74+
var baseType = typeof(BaseType);
75+
var iType = typeof(IType);
76+
77+
// act
78+
var baseResult = TypeHelper.ConvertType(val, baseType);
79+
var iResult = TypeHelper.ConvertType(val, iType);
80+
81+
// assert
82+
Assert.Equal(val, baseResult);
83+
Assert.Equal(val, iResult);
84+
}
85+
86+
private enum TestEnum
4887
{
4988
Test = 1
5089
}
90+
91+
private class ComplexType : BaseType
92+
{
93+
public int Property { get; set; }
94+
}
95+
96+
private class BaseType : IType
97+
{ }
98+
99+
private interface IType
100+
{ }
51101
}
52102
}

0 commit comments

Comments
 (0)