2 // PropertyBuilderTest.cs - NUnit Test Cases for the PropertyBuilder class
4 // Zoltan Varga (vargaz@freemail.hu)
6 // (C) Ximian, Inc. http://www.ximian.com
9 using System.Threading;
10 using System.Reflection;
11 using System.Reflection.Emit;
12 using System.Runtime.CompilerServices;
14 using NUnit.Framework;
16 namespace MonoTests.System.Reflection.Emit
20 public class PropertyBuilderTest : Assertion
22 private TypeBuilder tb;
24 private ModuleBuilder module;
27 protected void SetUp () {
28 AssemblyName assemblyName = new AssemblyName();
29 assemblyName.Name = "MonoTests.System.Reflection.Emit.PropertyBuilderTest";
31 AssemblyBuilder assembly
32 = Thread.GetDomain().DefineDynamicAssembly(
33 assemblyName, AssemblyBuilderAccess.Run);
35 module = assembly.DefineDynamicModule("module1");
37 tb = module.DefineType("class1",
38 TypeAttributes.Public);
42 public void TestProperties () {
44 FieldBuilder propField = tb.DefineField("propField",
46 FieldAttributes.Private);
48 PropertyBuilder property =
49 tb.DefineProperty ("prop", PropertyAttributes.HasDefault, typeof (int), new Type [0] { });
50 property.SetConstant (44);
52 MethodBuilder propertyGet = tb.DefineMethod("GetProp",
53 MethodAttributes.Public,
58 ILGenerator il = propertyGet.GetILGenerator();
60 il.Emit(OpCodes.Ldarg_0);
61 il.Emit(OpCodes.Ldfld, propField);
65 MethodBuilder propertySet = tb.DefineMethod("SetProp",
66 MethodAttributes.Public,
68 new Type[] { typeof(int) });
70 ILGenerator il = propertySet.GetILGenerator();
72 il.Emit(OpCodes.Ldarg_0);
73 il.Emit(OpCodes.Ldarg_1);
74 il.Emit(OpCodes.Stfld, propField);
78 property.SetGetMethod(propertyGet);
79 property.SetSetMethod(propertySet);
81 Type t = tb.CreateType ();
83 PropertyInfo[] props = t.GetProperties (BindingFlags.Public|BindingFlags.Instance);
84 AssertEquals (1, props.Length);
86 PropertyInfo p = t.GetProperty ("prop");
88 AssertEquals (PropertyAttributes.HasDefault, p.Attributes);
89 AssertEquals (true, p.CanRead);
90 AssertEquals (true, p.CanWrite);
91 AssertEquals ("prop", p.Name);
92 AssertEquals (MemberTypes.Property, p.MemberType);
93 AssertEquals (typeof (int), p.PropertyType);
94 MethodInfo[] methods = p.GetAccessors ();
95 AssertEquals (2, methods.Length);
96 AssertNotNull (p.GetGetMethod ());
97 AssertNotNull (p.GetSetMethod ());
99 object o = Activator.CreateInstance (t);
100 p.SetValue (o, 42, null);
101 AssertEquals (42, p.GetValue (o, null));