public void ToBeSame_DifferentReferences_Fails() { var a = new SomeClass(); var b = new SomeClass(); Expect(b).ToBeSame(a); }
public void ToNotBeSame_SameReferences_IsSuccess() { var a = new SomeClass(); var b = a; Expect(b).ToNotBeSame(a); }
public void Test_ConstIntFieldSetter(InteropAccessMode opt) { try { string script = @" myobj.ConstIntProp = 1; return myobj.ConstIntProp;"; Script S = new Script(); SomeClass obj = new SomeClass() { IntProp = 321 }; UserData.UnregisterType<SomeClass>(); UserData.RegisterType<SomeClass>(opt); S.Globals.Set("myobj", UserData.Create(obj)); DynValue res = S.DoString(script); Assert.AreEqual(DataType.Number, res.Type); Assert.AreEqual(115, res.Number); } catch (ScriptRuntimeException) { return; } Assert.Fail(); }
public Action ViaExpression() { FieldInfo field = typeof (SomeClass).GetField("field", BindingFlags.NonPublic | BindingFlags.Instance); ParameterExpression xValue = Expression.Parameter(typeof (object)); ParameterExpression xContainer = Expression.Parameter(typeof (object)); ParameterExpression xTypedContainer = Expression.Parameter(typeof (SomeClass)); Expression<Func<object, object, object>> xSetField = Expression .Lambda<Func<object, object, object>>( Expression.Block(new[] { xTypedContainer }, Expression.Assign( xTypedContainer, Expression.Convert(xContainer, typeof (SomeClass))), Expression.Assign( Expression.Field(xTypedContainer, field), Expression.Convert(xValue, typeof (int))), Expression.Convert(xTypedContainer, typeof (object))), xContainer, xValue); object someClass = new SomeClass(); Func<object, object, object> setFieldDelegate = xSetField.Compile(); return () => { for (int i = 0; i < iterationCount; i++) someClass = setFieldDelegate(someClass, i); }; }
public Entity ReplaceSomeClass(SomeClass newValue) { var component = CreateComponent<SomeClassComponent>(ComponentIds.SomeClass); component.value = newValue; ReplaceComponent(ComponentIds.SomeClass, component); return this; }
public void When_getting_controller_attributes_then_builds_up_instance() { using (var container = new UnityContainer()) { // Arrange var someInstance = new SomeClass(); container.RegisterInstance<ISomeInterface>(someInstance); container.RegisterType<TestFilterAttribute>(new InjectionProperty("Some")); var context = new ControllerContext { Controller = new ControllerWithTypeAttribute() }; var controllerDescriptor = new ReflectedControllerDescriptor(context.Controller.GetType()); var action = context.Controller.GetType().GetMethod("MyActionMethod"); var actionDescriptor = new ReflectedActionDescriptor(action, "MyActionMethod", controllerDescriptor); var provider = new UnityFilterAttributeFilterProvider(container); // Act Filter filter = provider.GetFilters(context, actionDescriptor).Single(); // Assert TestFilterAttribute attrib = filter.Instance as TestFilterAttribute; Assert.IsNotNull(attrib); Assert.AreEqual(FilterScope.Controller, filter.Scope); Assert.AreEqual(1234, filter.Order); Assert.AreSame(someInstance, attrib.Some); } }
public void SetUp() { someClass = new SomeClass(); var field = typeof (SomeClass).GetField("field", BindingFlags.NonPublic | BindingFlags.Instance); var xValue = Expression.Parameter(typeof (object)); var xContainer = Expression.Parameter(typeof (object)); var xTypedContainer = Expression.Parameter(typeof (SomeClass)); var xSetField = Expression .Lambda<Func<object, object, object>>( Expression.Block(new[] { xTypedContainer }, Expression.Assign( xTypedContainer, Expression.Convert(xContainer, typeof (SomeClass))), Expression.Assign( Expression.Field(xTypedContainer, field), Expression.Convert(xValue, typeof (int))), Expression.Convert(xTypedContainer, typeof (object))), xContainer, xValue); setViaExpression = xSetField.Compile(); var memberAccessor = FieldAccessorBuilder.BuildFor(typeof (SomeClass), field, true); setViaEmit = memberAccessor.SetMember; setViaReflection = (container, value) => { field.SetValue(container, value); return container; }; }
public void Test_NIntPropertyGetter(InteropAccessMode opt) { string script = @" x = myobj1.NIntProp; y = myobj2.NIntProp; return x,y;"; Script S = new Script(); SomeClass obj1 = new SomeClass() { NIntProp = 321 }; SomeClass obj2 = new SomeClass() { NIntProp = null }; UserData.UnregisterType<SomeClass>(); UserData.RegisterType<SomeClass>(opt); S.Globals.Set("myobj1", UserData.Create(obj1)); S.Globals.Set("myobj2", UserData.Create(obj2)); DynValue res = S.DoString(script); Assert.AreEqual(DataType.Tuple, res.Type); Assert.AreEqual(321.0, res.Tuple[0].Number); Assert.AreEqual(DataType.Number, res.Tuple[0].Type); Assert.AreEqual(DataType.Nil, res.Tuple[1].Type); }
public void Nuller_can_process_object_by_reference() { var someClass = new SomeClass{FakeProp1="Test"}; var processor = new TestProcessor(); processor.Process(someClass); Assert.IsNull(someClass.FakeProp1); }
public void Interop_Event_TwoObjects() { int invocationCount = 0; UserData.RegisterType<SomeClass>(); UserData.RegisterType<EventArgs>(); Script s = new Script(CoreModules.None); var obj = new SomeClass(); var obj2 = new SomeClass(); s.Globals["myobj"] = obj; s.Globals["myobj2"] = obj2; s.Globals["ext"] = DynValue.NewCallback((c, a) => { invocationCount += 1; return DynValue.Void; }); s.DoString(@" function handler(o, a) ext(); end myobj.MyEvent.add(handler); "); obj.Trigger_MyEvent(); obj2.Trigger_MyEvent(); Assert.AreEqual(1, invocationCount); }
private static SomeClass CreateData() { var source = new SomeClass { Property = new SomeClass2[2000000] }; for (int i = 0; i < source.Property.Length; i++) source.Property[i] = new SomeClass2 { field = i.ToString() }; return source; }
public void ThrowsExceptionWithNiceMessageWhenTrivialConversionCouldNotBeCompleted() { var instance = new SomeClass(); var ex = Assert.Throws<FeatureExecutionException>(() => sut.SetValue(instance, typeof(SomeClass).GetProperty("AnotherProperty"), "yo!")); Assert.AreEqual("The value 'yo!' could not be automatically converted to target type Int32 (AnotherProperty property of SomeClass)", ex.Message); }
void Start() { // our context can be any type at all var someClass = new SomeClass(); // the initial state has to be passed to the constructor _machine = new SKStateMachine<SomeClass>( someClass, new PatrollingState() ); }
public void Should_name_class_in_exception() { var someObject = new SomeClass(); const string str = default(string); Action act = () => str.DoIfNotNull(strange => someObject.SomeProperty = strange, false); act.ShouldThrow<NullReferenceException>() .Where(e => e.Message.Contains("System.String")); }
public void PerformanceComparison() { // Demonstrating the performance difference of three approaches to getting the values of properties const int iterations = 10000000; var obj = new SomeClass(); var s = new Stopwatch(); // First just go through PropertyInfo.GetValue Console.Out.Write("PropertyInfo.GetValue: "); PropertyInfo prop = obj.GetType().GetProperty("Val"); s.Reset(); s.Start(); for (int i = 0; i < iterations; i++) { prop.GetValue(obj, null); } s.Stop(); Console.Out.WriteLine(s.ElapsedMilliseconds); // Second, create a delegate to get the property directly from the getter method Console.Out.Write("Delegate getter: "); var getMethod = prop.GetGetMethod(); Func<SomeClass, string> typedGetter = (Func<SomeClass, string>)Delegate.CreateDelegate(typeof(Func<SomeClass, string>), null, getMethod); Func<object, object> delegateGetter = o => typedGetter((SomeClass)o); s.Reset(); s.Start(); for (int i = 0; i < iterations; i++) { delegateGetter(obj); } s.Stop(); Console.Out.WriteLine(s.ElapsedMilliseconds); // Thirdly, create a dynamic method to get the property Console.Out.Write("IL getter: "); DynamicMethod dynamicMethod = new DynamicMethod("", typeof(object), new Type[] { typeof(object) }, typeof(SomeClass), true); ILGenerator ilGenerator = dynamicMethod.GetILGenerator(); ilGenerator.Emit(OpCodes.Ldarg_0); ilGenerator.Emit(OpCodes.Call, getMethod); if (prop.PropertyType.IsValueType) { ilGenerator.Emit(OpCodes.Box, prop.PropertyType); } ilGenerator.Emit(OpCodes.Ret); var ilGetter = (Func<object, object>)dynamicMethod.CreateDelegate(typeof(Func<object, object>)); s.Reset(); s.Start(); for (int i = 0; i < iterations; i++) { ilGetter(obj); } s.Stop(); Console.Out.WriteLine("IL getter: " + s.ElapsedMilliseconds); }
public void SetsPropertyOnInstanceLikeExpected() { var instance = new SomeClass(); // propertyof(SomeClass.SomeProperty) would be nice... sut.SetValue(instance, typeof(SomeClass).GetProperty("SomeProperty"), "yo!"); Assert.AreEqual("yo!", instance.SomeProperty); }
public void serializes_the_class_name() { var someClass = new SomeClass(); var serializer = new Serializer(); var serializedString = serializer.Serialize(someClass); serializedString.Should().Be("SomeClass"); }
public static void The_ReferenceEquals_Method() { SomeClass class1 = new SomeClass(); SomeClass class2 = new SomeClass(); bool b1 = ReferenceEquals(null, null); bool b2 = ReferenceEquals(class1, null); bool b3 = ReferenceEquals(class1, class2); // class1 和 class2 指向不同的对象 Console.WriteLine("{0} {1} {2}", b1, b2, b3); // 输出true false false }
private static SomeClass CreateData() { var source = new SomeClass { Property = Enumerable.Range(0, blobSize) .Select(i => new SomeClass2 { field = new SomeClass3 { field = i.ToString() } }) .ToArray() }; return source; }
public void CanValidatePropertyUsingItsName() { var validator = new Mock<IValidator>(); var obj = new SomeClass(); ValidationContext.Ensure(obj) .ItsProperty<string>("Name", x => x.IsValid(validator.Object)); validator.Verify(x => x.Validate(ValidationContext, obj.Name)); }
public void CanValidatePropertyUsingStronglyTypedSyntax() { var validator = new Mock<IValidator>(); var obj = new SomeClass(); ValidationContext.Ensure(obj) .ItsProperty(x => x.Name, x => x.IsValid(validator.Object)); validator.Verify(x => x.Validate(ValidationContext, obj.Name)); }
public void CanClassReturnValueReturn() { var sc = new SomeClass { SomeString = TestValue, SomeValue = 5 }; Assert.AreEqual(sc.ToMaybe().Return(x => x.SomeString, "Test"), TestValue); }
public void CanClassReturnValueWhenClassIsNullReturn() { var sc = new SomeClass { SomeString = null, SomeValue = 5 }; Assert.AreEqual(sc.ToMaybe().With(x => x.SomeString).Return(x => x, TestKey), TestKey); }
public void CanClassReturnValueWith() { var sc = new SomeClass { SomeString = TestValue, SomeValue = 5 }; Assert.AreEqual(sc.ToMaybe().With(x => x.SomeString).Value, TestValue); }
void Start() { // our context can be any type at all var someClass = new SomeClass(); // the initial state has to be passed to the constructor _machine = new SKStateMachine<SomeClass>( someClass, new PatrollingState() ); // another option is to pass the type of the initial state to the constructor //_machine = new SKStateMachine<SomeClass>( someClass, typeof( PatrollingState ) ); }
public void Exclude_can_process_IEnumerable_Dot() { var target = new SomeClass { ListProp = new List<SomeClass> { new SomeClass { FakeProp1 = "F11", FakeProp2 = "F21" }, new SomeClass { FakeProp1 = "F21", FakeProp2 = "F22" }, new SomeClass { FakeProp1 = "F31", FakeProp2 = "F32" }, new SomeClass { FakeProp1 = "F41", FakeProp2 = "F42" } } }; var instruction = "ListProp.SomeClass.FakeProp2"; var result = Nuller.Exclude<SomeClass> (target, instruction); foreach (var r in result.ListProp) { Assert.IsNull (r.FakeProp2); } }
public void T02_Interface() { var container = new Container(log: Write); var instance = new SomeClass(); container.RegisterInstance<ISomeClass>(instance); var instance1 = container.Resolve<ISomeClass>(); Assert.Equal(instance, instance1); var instance2 = container.Resolve<ISomeClass>(); Assert.Equal(instance1, instance2); Assert.Throws<TypeAccessException>(() => container.Resolve<SomeClass>()); Assert.Throws<TypeAccessException>(() => container.RegisterInstance<ISomeClass>(instance)).WriteMessageTo(Write); }
public void CreatesGetterExpression() { var propInfo = typeof(SomeClass).GetProperties().First(); var testee = new SourceValue<SomeClass>(propInfo); var expr = testee.CreateGetter() as Expression<Func<SomeClass, string>>; var sourceInstance = new SomeClass {A = "test"}; Assert.AreEqual("test", expr.Compile()(sourceInstance)); }
/// <summary> /// Standard function for tests /// </summary> /// <exception cref="IOException">I/O exception occured. </exception> /// <exception cref="Exception">A delegate callback throws an exception.</exception> public static void RunTests () { try { SomeClass c = new SomeClass {SomeString = "Some string"}; c.Changed += DisplayMessage; c.Cleared += DisplayMessage; c.SomeString = "Some changed string"; c.SomeString = ""; } catch (IOException e) { Console.WriteLine (e); } }
public void Test_Serialize_Deserialize() { IObjectSerializer serializer = new MsDataContractJsonSerializer(); var someClass = new SomeClass {SomeProperty = "SomeStringValue"}; var jsonStr = serializer.SerializeObject(someClass); var someClass2 = serializer.DeserializeObject<SomeClass>(jsonStr); Assert.AreNotEqual(someClass.GetHashCode(), someClass2.GetHashCode()); Assert.AreEqual(someClass.SomeProperty, someClass2.SomeProperty); }
public void TestMethod7() { Assert.AreEqual(SomeClass.Propys2(0), "нуль"); }
public void TestMethod1() { Assert.AreEqual(SomeClass.Days(7), "Sunday"); }
public void TestMethod8() { Assert.AreEqual(SomeClass.Propys2(123654733001), "сто двадцять три мільярди шістсот п'ятдесят чотири мільйони сімсот тридцять три тисячі один"); }
public static StringBuilder ConcatS(int p1, string p2, IComparable p3, bool p4, List <object> p5, IEnumerable <object> p6, StringBuilder p7, Dictionary <object, object> p8, SomeClass p9, int p10 = 1994) { p7.Append(p1); p7.Append(p2); p7.Append(p3); p7.Append(p4); p7.Append("|"); foreach (var o in p5) { p7.Append(o); } p7.Append("|"); foreach (var o in p6) { p7.Append(o); } p7.Append("|"); foreach (var o in p8.Keys.OrderBy(x => x.ToString())) { p7.Append(o); } p7.Append("|"); foreach (var o in p8.Values.OrderBy(x => x.ToString())) { p7.Append(o); } p7.Append("|"); p7.Append(p9); p7.Append(p10); return(p7); }
public void ReturnNullIfValueIsNullForIndexer() { SomeClass sc = null; Assert.Null(sc?["Bob"]); }
public void TestMethod5() { Assert.AreEqual(SomeClass.Propys2(32), "тридцять два"); }
public void SomeTest() { var classUnderTest = new SomeClass(thingRepository, entityRepository); Assert.AreEqual(classUnderTest.FetchEntitiesForThing(1).Count, 3); }
public void TestMethod2() { Assert.AreEqual(SomeClass.Days(1), "Monday"); }
public void TestMethod4() { Assert.AreEqual(SomeClass.Propys2(341), "триста сорок один"); }
public void TestMethod10() { Assert.AreEqual(SomeClass.Propys2(1236547330019), "введіть коректне число"); }
public MyClass2(SomeClass someClass) { this._someClass = someClass; }
public void TestMethod11() { Assert.AreEqual(SomeClass.Propys2(701225513), "сімсот один мільйон двісті двадцять п'ять тисяч п'ятсот тринадцять"); }
public void TestSomeOtherLogic2() { Assert.AreEqual(SomeClass.Logic(0, 0), 0); }
private void SomeOtherTest() { var classUnderTest = new SomeClass(thingRepository, entityRepository); Assert.AreEqual(classUnderTest.FetchEntitiesForThing(2).Count, 1); }
public void TestInitialize() { this.mockSomeClass = Mock.Create <SomeClass>(); }
public void TestMethod3() { Assert.AreEqual(SomeClass.Propys2(110), "сто десять"); }
public void TestMethod6() { Assert.AreEqual(SomeClass.Propys2(9999), "дев'ять тисяч дев'ятсот дев'яносто дев'ять"); }
public void TestMethod1() { Assert.AreEqual(SomeClass.Propys2(7), "сім"); }
public void TestMethod9() { Assert.AreEqual(SomeClass.Propys2(123000000001), "сто двадцять три мільярди один"); }
public void Main() { var a = new SomeClass() { SomeString = "a", SomeInt = 0, SomeFloat = 0.0F, IntList = new List <int>(), ClassList = new List <SomeClass>(), ValueDict = new Dictionary <int, int>(), ClassDict = new Dictionary <int, SomeClass>(), WeirdDict = new Dictionary <SomeClass, SomeClass>(), SomeOtherClass = null, }; var b = new SomeClass() { SomeString = "bb", SomeInt = 1, SomeFloat = 1.0F, IntList = new List <int>(), ClassList = new List <SomeClass>(), ValueDict = new Dictionary <int, int>(), ClassDict = new Dictionary <int, SomeClass>(), WeirdDict = new Dictionary <SomeClass, SomeClass>(), SomeOtherClass = a, }; var members = PropertyAndFieldCache.Get(typeof(SomeClass)); //Test inherited property detection: Assert.Contains(members, x => x.Name == "SomeOtherString"); Assert.Contains(members, x => x.Name == nameof(SomeBaseClass.SomeString)); //Test Get: var someStringProp = members.First(x => x.Name.Contains("SomeString")); Assert.Equal("bb", someStringProp.GetVal(b)); Assert.Equal("a", someStringProp.GetVal(a)); //Test Set: someStringProp.SetVal(b, "c"); Assert.Equal("c", b.SomeString); //Test Classification: Assert.Equal(15, members.Count()); Assert.Equal(11, members.Where(x => x.IsProperty && x.IsPublic).Count()); Assert.Equal(2, members.Where(x => x.IsDictionaryOfClass).Count()); Assert.Single(members.Where(x => x.IsIEnumberableOfClass)); Assert.Equal(2, members.Where(x => x.IsClass).Count()); Assert.Single(members.Where(x => x.IsDictionaryOfValueOrString)); Assert.Single(members.Where(x => x.IsIEnumberableOfValueOrString)); Assert.Equal(8, members.Where(x => x.IsValueOrString).Count()); foreach (var prop in members) { prop.Copy(b, a); } Assert.Equal(a.ClassDict, b.ClassDict); Assert.Equal(a.ClassList, b.ClassList); Assert.Equal(a.IntList, b.IntList); Assert.Equal(a.SomeFloat, b.SomeFloat); Assert.Equal(a.SomeInt, b.SomeInt); Assert.Equal(a.SomeString, b.SomeString); Assert.Equal(a.ValueDict, b.ValueDict); Assert.Equal(a.WeirdDict, b.WeirdDict); //Test IsEqual foreach (var prop in members) { Assert.True(prop.IsEqual(a, b)); } //Test string conversions. foreach (var prop in members) { if (prop.IsStringConvertible) { var s = prop.GetValAsString(a); prop.SetValFromString(a, s); } } foreach (var prop in members) { Assert.True(prop.IsEqual(a, b)); } //Test double conversions. foreach (var prop in members) { if (prop.IsDoubleConvertible) { var d = prop.GetValAsDouble(a); prop.SetValFromDouble(a, d); } } foreach (var prop in members) { Assert.True(prop.IsEqual(a, b)); } //Test Markers Assert.Single(members.Where(x => x.Markers.Contains("Special!"))); Assert.Single(members.Where(x => x.Markers.Contains("Multiple"))); Assert.Single(members.Where(x => x.Markers.Contains("extends"))); }
static void Main() { SomeClass <object> x = new SomeClass <object> (); x.Foo(); }
public void ReturnNullIfValueIsNull() { SomeClass sc = null; Assert.Null(sc?.GetAFive()); }
public void TestMethod2() { Assert.AreEqual(SomeClass.Propys2(14), "чотирнадцять"); }
public void CallMemberIfValueIsNotNull() { SomeClass sc = new SomeClass(); Assert.Equal(5, sc?.GetAFive()); }
public static void ComplicatedMethod(IList <string> arg, SomeClass objArg) { }
public StringBuilder ConcatI(Script s, int p1, string p2, IComparable p3, bool p4, List <object> p5, IEnumerable <object> p6, StringBuilder p7, Dictionary <object, object> p8, SomeClass p9, int p10 = 1912) { Assert.IsNotNull(s); return(ConcatS(p1, p2, p3, p4, p5, p6, p7, p8, this, p10)); }
public void TestPropertyWithPrivateSetter() { SomeClass obj = new SomeClass(); Assert.That(obj.BrokenProp, Is.EqualTo(string.Empty)); }
public void MethodTiming() { FooMethods pinvoke_methods; foo_get_methods(out pinvoke_methods); DV p_instance_void = (DV)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_void, typeof(DV)); DI p_instance_int = (DI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_int, typeof(DI)); DP p_instance_ptr = (DP)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.instance_ptr, typeof(DP)); DV1A p_void_1a = (DV1A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_1_args, typeof(DV1A)); DV2A p_void_2a = (DV2A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_2_args, typeof(DV2A)); DV3A p_void_3a = (DV3A)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_3_args, typeof(DV3A)); DV1AI p_void_1ai = (DV1AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_1_iargs, typeof(DV1AI)); DV2AI p_void_2ai = (DV2AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_2_iargs, typeof(DV2AI)); DV3AI p_void_3ai = (DV3AI)Marshal.GetDelegateForFunctionPointer(pinvoke_methods.void_3_iargs, typeof(DV3AI)); IntPtr obj_class = JNIEnv.FindClass("java/lang/Object"); IntPtr obj_init = JNIEnv.GetMethodID(obj_class, "<init>", "()V"); var ownership = JniHandleOwnership.DoNotTransfer; Java.Lang.Object jobj1 = new Java.Lang.Object(JNIEnv.NewObject(obj_class, obj_init), ownership), jobj2 = new Java.Lang.Object(JNIEnv.NewObject(obj_class, obj_init), ownership), jobj3 = new Java.Lang.Object(JNIEnv.NewObject(obj_class, obj_init), ownership); SomeClass obj1 = new SomeClass(), obj2 = new SomeClass(), obj3 = new SomeClass(); var j = new Com.Xamarin.Android.Timing(); var m = new ManagedTiming(); var comparisons = new[] { new { Name = "static void", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod()), Managed = A(() => ManagedTiming.StaticVoidMethod()), Pinvoke = A(() => foo_void_timing()), }, new { Name = "static int", Jni = A(() => Com.Xamarin.Android.Timing.StaticIntMethod()), Managed = A(() => ManagedTiming.StaticIntMethod()), Pinvoke = A(() => foo_int_timing()), }, new { Name = "static object", Jni = A(() => Com.Xamarin.Android.Timing.StaticObjectMethod()), Managed = A(() => ManagedTiming.StaticObjectMethod()), Pinvoke = A(() => foo_ptr_timing()), }, new { Name = "virtual void", Jni = A(() => j.VirtualVoidMethod()), Managed = A(() => m.VirtualVoidMethod()), Pinvoke = A(() => p_instance_void()), }, new { Name = "virtual int", Jni = A(() => j.VirtualIntMethod()), Managed = A(() => m.VirtualIntMethod()), Pinvoke = A(() => p_instance_int()), }, new { Name = "virtual object", Jni = A(() => j.VirtualObjectMethod()), Managed = A(() => m.VirtualObjectMethod()), Pinvoke = A(() => p_instance_ptr()), }, new { Name = "final void", Jni = A(() => j.FinalVoidMethod()), Managed = A(() => m.FinalVoidMethod()), Pinvoke = A(null), }, new { Name = "final int", Jni = A(() => j.FinalIntMethod()), Managed = A(() => m.FinalIntMethod()), Pinvoke = A(null), }, new { Name = "final object", Jni = A(() => j.FinalObjectMethod()), Managed = A(() => m.FinalObjectMethod()), Pinvoke = A(null), }, new { Name = "static void o1", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod1Args(jobj1)), Managed = A(() => ManagedTiming.StaticVoidMethod1Args(obj1)), Pinvoke = A(() => { // We include timing of the GCHandle manipulation since // a JNI invocation has to do similar work, and pinning // is usually always needed for P/Invokes. GCHandle h1 = GCHandle.Alloc(obj1, GCHandleType.Pinned); IntPtr addr1 = h1.AddrOfPinnedObject(); p_void_1a(addr1); h1.Free(); }), }, new { Name = "static void o2", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod2Args(jobj1, jobj2)), Managed = A(() => ManagedTiming.StaticVoidMethod2Args(obj1, obj2)), Pinvoke = A(() => { GCHandle h1 = GCHandle.Alloc(obj1, GCHandleType.Pinned), h2 = GCHandle.Alloc(obj2, GCHandleType.Pinned); IntPtr addr1 = h1.AddrOfPinnedObject(), addr2 = h2.AddrOfPinnedObject(); p_void_2a(addr1, addr2); h1.Free(); h2.Free(); }), }, new { Name = "static void o3", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod3Args(jobj1, jobj2, jobj3)), Managed = A(() => ManagedTiming.StaticVoidMethod3Args(obj1, obj2, obj3)), Pinvoke = A(() => { GCHandle h1 = GCHandle.Alloc(obj1, GCHandleType.Pinned), h2 = GCHandle.Alloc(obj2, GCHandleType.Pinned), h3 = GCHandle.Alloc(obj3, GCHandleType.Pinned); IntPtr addr1 = h1.AddrOfPinnedObject(), addr2 = h2.AddrOfPinnedObject(), addr3 = h3.AddrOfPinnedObject(); p_void_3a(addr1, addr2, addr3); h1.Free(); h2.Free(); h3.Free(); }), }, new { Name = "static void i1", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod1IArgs(42)), Managed = A(() => ManagedTiming.StaticVoidMethod1IArgs(42)), Pinvoke = A(() => p_void_1ai(42)), }, new { Name = "static void i2", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod2IArgs(42, 42)), Managed = A(() => ManagedTiming.StaticVoidMethod2IArgs(42, 42)), Pinvoke = A(() => p_void_2ai(42, 42)), }, new { Name = "static void i3", Jni = A(() => Com.Xamarin.Android.Timing.StaticVoidMethod3IArgs(42, 42, 42)), Managed = A(() => ManagedTiming.StaticVoidMethod3IArgs(42, 42, 42)), Pinvoke = A(() => p_void_3ai(42, 42, 42)), }, }; const int count = 100000; foo_init(JNIEnv.Handle); var jniTimes = new long [comparisons.Length]; foo_get_native_jni_timings(JNIEnv.Handle, count, j.Class.Handle, j.Handle, jniTimes); int jniTimeIndex = 0; foreach (var c in comparisons) { var jw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < count; ++i) { c.Jni(); } jw.Stop(); var mw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < count; ++i) { c.Managed(); } mw.Stop(); System.Diagnostics.Stopwatch pw = null; if (c.Pinvoke != null) { pw = System.Diagnostics.Stopwatch.StartNew(); for (int i = 0; i < count; ++i) { c.Pinvoke(); } pw.Stop(); } string message = string.Format("Method Invoke: {0}: JNI is {1}x managed", c.Name, System.Math.Round(jw.Elapsed.TotalMilliseconds / mw.Elapsed.TotalMilliseconds)); Console.WriteLine(message); var ct = TimeSpan.FromMilliseconds(jniTimes [jniTimeIndex++]); Console.WriteLine("\t C/JNI: {0} ms | average: {1} ms", FormatFraction(ct.TotalMilliseconds, 10, 5), FormatFraction(ct.TotalMilliseconds / count, 12, 5)); Console.WriteLine("\t JNI: {0} ms; {1,3}x C/JNI | average: {2} ms", FormatFraction(jw.Elapsed.TotalMilliseconds, 10, 5), ToString(jw.Elapsed, ct), FormatFraction(jw.Elapsed.TotalMilliseconds / count, 12, 5)); Console.WriteLine("\tManaged: {0} ms | average: {1} ms", FormatFraction(mw.Elapsed.TotalMilliseconds, 10, 5), FormatFraction(mw.Elapsed.TotalMilliseconds / count, 12, 5)); if (pw != null) { Console.WriteLine("\tPinvoke: {0} ms; {1,3}x managed | average: {2} ms", FormatFraction(pw.Elapsed.TotalMilliseconds, 10, 5), ToString(pw.Elapsed, mw.Elapsed), FormatFraction(pw.Elapsed.TotalMilliseconds / count, 12, 5)); } } }
private void DoSomething() { var sc = new SomeClass(); }
public void TestMethod3() { Assert.AreEqual(SomeClass.Days(9), "wrong number"); }