Search Unity

Reflection under Unit Test

Discussion in 'Testing & Automation' started by ceceomer, Oct 14, 2021.

  1. ceceomer

    ceceomer

    Joined:
    Sep 1, 2014
    Posts:
    24
    I get null object when I am trying to reflect class's static method under unit test. But it ok under editor's Play Mode. My platform settings: Android, IL2CPP and .Net4.xHere is my class:
    Code (CSharp):
    1.  
    2. namespace Core.Easing
    3. {
    4. public class EasingFunction
    5. {
    6.         public static float EaseNone(float t, float b, float c, float d)
    7.         {
    8.             return c * t / d + b;
    9.         }
    10. }
    11. }
    12.  
    and here is my reflection method:
    Code (CSharp):
    1.        
    2. public Func<float, float, float, float, float> Build()
    3.         {
    4.             var namespaceName = "Core.Easing";
    5.             var className = "EasingFunction";
    6.             var easeMethodName = "EaseNone";
    7.  
    8.             var implType = Assembly.GetExecutingAssembly().GetType(namespaceName + "." + className);
    9.             //var implType = Type.GetType(namespaceName + "." + className);//Also not working
    10.             var implMethod = implType.GetMethod(easeMethodName, BindingFlags.Public | BindingFlags.Static);
    11.             var res = Delegate.CreateDelegate(typeof(Func<float, float, float, float, float>), implMethod);
    12.             return (Func<float, float, float, float, float>)res.Clone();
    13.         }
    14.  
    So, Each class has its own asmdef file and these are included in the unit test. I looked at the constraints from Unity's documentation but couldn't find an answer.
     
  2. VolodymyrBS

    VolodymyrBS

    Joined:
    May 15, 2019
    Posts:
    150
    One of reason I could think about is Unity stript out EasingFunction class when build for il2cpp. you could try to add Preserve attribute to EasingFunction.
     
  3. ceceomer

    ceceomer

    Joined:
    Sep 1, 2014
    Posts:
    24
    Thank you for answer but not working. I added "[assembly: Preserve]" attribute on namespace level (Core.Easing) but it didn't work. I got same error.


    at (wrapper managed-to-native) System.Reflection.MonoMethod.InternalInvoke(System.Reflection.MonoMethod,object,object[],System.Exception&)
    at System.Reflection.MonoMethod.Invoke (System.Object obj, System.Reflection.BindingFlags invokeAttr, System.Reflection.Binder binder, System.Object[] parameters, System.Globalization.CultureInfo culture) [0x00032] in <695d1cc93cca45069c528c15c9fdd749>:0