comparison UnitTests/CS/Reflection/ObjectFactoryAttributeTest.cs @ 0:f990fcb411a9

Копия текущей версии из github
author cin
date Thu, 27 Mar 2014 21:46:09 +0400
parents
children
comparison
equal deleted inserted replaced
-1:000000000000 0:f990fcb411a9
1 using System;
2
3 using NUnit.Framework;
4
5 using BLToolkit.Reflection;
6 using System.Reflection;
7 using System.Collections.Generic;
8 using BLToolkit.Mapping;
9
10 namespace Reflection
11 {
12 [TestFixture]
13 public class ObjectFactoryAttributeTest
14 {
15 [ObjectFactory(typeof(TestObject.Factory))]
16 public class TestObject
17 {
18 public TestObject()
19 {
20 throw new InvalidOperationException();
21 }
22
23 private TestObject(int n)
24 {
25 Number = n;
26 }
27
28 public int Number;
29
30 public class Factory : IObjectFactory
31 {
32 object IObjectFactory.CreateInstance(TypeAccessor typeAccessor, InitContext context)
33 {
34 return new TestObject(53);
35 }
36 }
37 }
38
39 [Test]
40 public void Test()
41 {
42 TestObject o = (TestObject)TypeAccessor.CreateInstanceEx(typeof(TestObject));
43
44 Assert.AreEqual(53, o.Number);
45 }
46
47 [ObjectFactory(typeof(Record.Factory))]
48 public class Record
49 {
50 public class Factory : IObjectFactory
51 {
52 #region IObjectFactory Members
53
54 public object CreateInstance(TypeAccessor typeAccessor, InitContext context)
55 {
56 Type t = typeAccessor.Type;
57
58 ConstructorInfo[] ctis = t.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic);
59 ConstructorInfo constructor = ctis[0];
60
61 foreach (ConstructorInfo ci in ctis)
62 {
63 if (constructor.GetParameters().Length < ci.GetParameters().Length)
64 constructor = ci;
65 }
66
67 ParameterInfo[] pis = constructor.GetParameters();
68 object[] param = new object[pis.Length];
69
70 for(int i = 0; i < pis.Length; i++)
71 {
72 ParameterInfo pi = pis[i];
73 Type pType = pi.ParameterType;
74 string pName = pi.Name;
75 int ordinal = context.DataSource.GetOrdinal(pName);
76
77 if (ordinal >= 0)
78 {
79 param[i] = context.MappingSchema.ConvertChangeType(
80 context.DataSource.GetValue(context.SourceObject, ordinal),
81 pType);
82 }
83 else
84 param[i] = context.MappingSchema.GetDefaultValue(pType);
85 }
86
87 context.StopMapping = true;
88
89 return constructor.Invoke(param);
90
91 }
92
93 #endregion
94 }
95
96 public Record(string name, int value)
97 {
98 _name = name;
99 _value = value;
100 }
101
102 private string _name;
103 public string Name { get { return _name; } }
104
105 private int _value;
106 public int Value { get { return _value; } }
107 }
108
109 [Test]
110 public void RecordFactoryTest()
111 {
112 Record s = new Record("Elvis", 101);
113 Record r = Map.ObjectToObject<Record>(s);
114
115 Assert.IsNotNull(r);
116
117 Assert.AreEqual(s.Value, r.Value);
118 Assert.AreEqual(s.Name, r.Name);
119 }
120 }
121 }