Skip to content

Commit a98d164

Browse files
authored
Simplify boxing + add tostring overloads for test case data (#2228)
1 parent 65e1cf5 commit a98d164

1 file changed

Lines changed: 13 additions & 32 deletions

File tree

Tests/Realm.Tests/Database/CollectionTests.cs

Lines changed: 13 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -19,6 +19,7 @@
1919
using System;
2020
using System.Collections.Generic;
2121
using System.Linq;
22+
using System.Reflection;
2223
using System.Threading.Tasks;
2324
using MongoDB.Bson;
2425
using NUnit.Framework;
@@ -426,6 +427,8 @@ public StringQueryNumericData(string propertyName, RealmValue valueToAddToDB, Re
426427
ValueToQueryFor = valueToQueryFor;
427428
ExpectedMatch = expectedMatch;
428429
}
430+
431+
public override string ToString() => $"{PropertyName}: '{ValueToAddToRealm}' should{(ExpectedMatch ? string.Empty : " NOT")} match '{ValueToQueryFor}': {ExpectedMatch}";
429432
}
430433

431434
public struct StringQueryTestData
@@ -441,44 +444,22 @@ public StringQueryTestData(string propertyName, RealmValue matchingValue, RealmV
441444
NonMatchingValue = nonMatchingValue;
442445
}
443446

447+
public override string ToString() => $"{PropertyName}, match: '{MatchingValue}' non-match: '{NonMatchingValue}'";
444448
}
445449

446-
public static object BoxValue(RealmValue val, Type targetType)
450+
private static object BoxValue(RealmValue val, Type targetType)
447451
{
448452
var boxed = val.AsAny();
453+
if (boxed != null && targetType.IsGenericType && targetType.GetGenericTypeDefinition() == typeof(RealmInteger<>))
454+
{
455+
var wrappedType = targetType.GetGenericArguments().Single();
456+
boxed = Convert.ChangeType(boxed, wrappedType);
457+
return Activator.CreateInstance(targetType, BindingFlags.Instance | BindingFlags.NonPublic, null, new[] { boxed }, null);
458+
}
459+
449460
if (boxed != null && boxed.GetType() != targetType)
450461
{
451-
try
452-
{
453-
boxed = Convert.ChangeType(boxed, targetType);
454-
}
455-
catch (System.InvalidCastException e)
456-
{
457-
if (e.Message.Contains("RealmInteger"))
458-
{
459-
var innerType = targetType.GenericTypeArguments.Single();
460-
if (innerType == typeof(int))
461-
{
462-
boxed = (RealmInteger<int>)val;
463-
}
464-
else if (innerType == typeof(long))
465-
{
466-
boxed = (RealmInteger<long>)val;
467-
}
468-
else if (innerType == typeof(byte))
469-
{
470-
boxed = (RealmInteger<byte>)val;
471-
}
472-
else if (innerType == typeof(short))
473-
{
474-
boxed = (RealmInteger<short>)val;
475-
}
476-
}
477-
else
478-
{
479-
throw e;
480-
}
481-
}
462+
return Convert.ChangeType(boxed, targetType);
482463
}
483464

484465
return boxed;

0 commit comments

Comments
 (0)