Skip to content

Instantly share code, notes, and snippets.

@brunomlopes
Last active June 2, 2022 10:17
Show Gist options
  • Save brunomlopes/521e0a5a05ad37eb9237542be7656ab2 to your computer and use it in GitHub Desktop.
Save brunomlopes/521e0a5a05ad37eb9237542be7656ab2 to your computer and use it in GitHub Desktop.
Test case for ConvertTo
public class TestConvertTo
{
public TestConvertTo()
{
// Adding this converter resolves the stack overflow, but it's not a generic solution
//IDictionary<string, string> Converter(Dictionary<string, string> input)
//{
// if(input == null) return null;
// return input.ToDictionary(kvp => kvp.Key, kvp => kvp.Value);
//}
//AutoMapping.RegisterConverter<Dictionary<string,string>, IDictionary<string,string>>(Converter);
}
[Fact()]
public void FromConcrete_ToInterface_PropertyIsNull_FailsWithStackOverflow()
{
var classBase = new ClassBase
{
PropertiesByName = null
};
var converted = classBase.ConvertTo<ClassToConvert>();
converted.ToJson().ShouldNotBeNullOrEmpty();
}
[Fact]
public void FromConcrete_ToInterface_PropertyIsNotNull_Works()
{
var classBase = new ClassBase
{
PropertiesByName = new Dictionary<string, string>
{
["key1"] = "value1",
["key2"] = "value2",
["key3"] = "value3"
}
};
var converted = classBase.ConvertTo<ClassToConvert>();
converted.ToJson().ShouldNotBeNullOrEmpty();
}
[Fact]
public void FromInterface_ToInterface_PropertyIsNotNull_Works()
{
var classBase = new ClassToConvert()
{
PropertiesByName = new Dictionary<string, string>
{
["key1"] = "value1",
["key2"] = "value2",
["key3"] = "value3"
}
};
var converted = classBase.ConvertTo<AnotherClassToConvert>();
converted.ToJson().ShouldNotBeNullOrEmpty();
}
[Fact]
public void FromInterface_ToInterface_PropertyIsNull_Works()
{
var classBase = new ClassToConvert
{
PropertiesByName = null
};
var converted = classBase.ConvertTo<AnotherClassToConvert>();
converted.ToJson().ShouldNotBeNullOrEmpty();
}
[Fact]
public void FromConcrete_ToConcrete_PropertyIsNull_Works()
{
var classBase = new ClassBase
{
PropertiesByName = null
};
var converted = classBase.ConvertTo<AnotherClassBase>();
converted.ToJson().ShouldNotBeNullOrEmpty();
}
[Fact]
public void FromConcrete_ToConcrete_PropertyIsNotNull_Works()
{
var classBase = new ClassBase
{
PropertiesByName = new Dictionary<string, string>
{
["key1"] = "value1",
["key2"] = "value2",
["key3"] = "value3"
}
};
var converted = classBase.ConvertTo<AnotherClassBase>();
converted.ToJson().ShouldNotBeNullOrEmpty();
}
}
public class ClassBase
{
public Dictionary<string, string> PropertiesByName { get; set; }
}
public class AnotherClassBase
{
public Dictionary<string, string> PropertiesByName { get; set; }
}
public class ClassToConvert
{
public IDictionary<string, string> PropertiesByName { get; set; }
}
public class AnotherClassToConvert
{
public IDictionary<string, string> PropertiesByName { get; set; }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment