问题描述
我有一些庞大的类,并且不想将它们全部写出来进行测试,因为这是一项巨大的工作,我会忘记一些使测试无效的值.
I have some huge classes and don't want to write them all out for testing, because it's a huge effort and I could forget some values what makes the test invalid.
Messages = new List<Request.Notif.NotifRuleMessages>
{
new Request.Notif.NotifRuleMessages
{
Code = 1234,
Message = new List<Request.Notif.NotifRuleMessagesMessage>
{
new Request.Notif.NotifMessagesMessage
{
Status = new Request.Notif.NotifMessagesMessageStatus
{
Code = 1,
Bool = true,
Test1 = "Test",
Test2 = "Test"
},
Rules = new List<Request.Notif.NotifMessagesMessageRule>
{
new Request.Notif.NotifMessagesMessageRule
{
Lengths = new Request.Notif.NotifMessagesMessageRuleLength
{
Lenght = 1,
Lengths = new List<Request.Notif.NotifMessagesMessageRuleLengthLength>
{
new Request.Notif.NotifMessagesMessageRuleLengthLength
{
Type = "Test",
Value = 1
}
}
},
Status = new List<Request.Notif.NotifMessagesMessageRuleStatus>
{
new Request.Notif.NotifMessagesMessageRuleStatus
{
Test1 = "Test",
Test2 = "Test"
有没有一种方法可以自动用1
或0
填充所有int
值,并用Test
填充所有string
值,尤其是具有正确的类的所有objects
,而无需进行单元测试和外部库?
Is there a way to automaticly fill all int
values with 1
or 0
and all string
values with Test
and especially all objects
with the right class without unit testing and external libs?
推荐答案
使用反射,您可以递归地填充对象并设置选择的默认值.一个可以帮助您完成此任务的帮助函数的小例子:
Using reflection you could populate your objects recursively and set whatever default values you choose. A small example of a helper function that could do that for you:
void SetDefaults(object testObj)
{
var props = testObj.GetType().GetProperties();
foreach (var prop in props)
{
if (prop.GetSetMethod() == null)
{
continue;
}
var propType = prop.PropertyType;
if (propType == typeof(int))
{
prop.SetValue(testObj, 1);
}
else if (propType == typeof(bool))
{
prop.SetValue(testObj, false);
}
// More conditions...
else
{
var ctor = propType.GetConstructor(Type.EmptyTypes);
var propertyObject = ctor.Invoke(new object[0]);
SetDefaults(propertyObject);
prop.SetValue(testObj, propertyObject);
}
}
}
如您所见,如果您的对象树使用没有默认构造函数(无参数构造函数)的类型,则在else
-条件下需要一些更复杂的逻辑.基本上,这里发生的事情是依赖注入框架中发生的事情的非常简化的版本.
As you can see, if your tree of objects use types that don't have default constructors (parameterless constructors) you need some more complicated logic in the else
-condition. Basically the stuff going on here is a very simplified version of what happens in a dependency injection framework.
要使用它,请执行以下操作:
To use it, do something like:
void Main()
{
TestObject obj = new TestObject();
SetDefaults(obj);
Console.WriteLine(obj);
}
class TestObject {
public int MyInt { get; set; }
public SubTestObject SubObj { get; set; }
}
class SubTestObject {
public int MyOwnInt { get; set; }
public bool MyBoolGetter => 1 > 0;
}
这篇关于在类中插入值而无需显式编写它们的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!