No Description
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

MonoBehaviourTest.cs 2.7KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. using System;
  2. namespace UnityEngine.TestTools
  3. {
  4. /// <summary>
  5. /// This is a wrapper that allows running tests on MonoBehaviour scripts. Inherits from <see cref="CustomYieldInstruction"/> `MonoBehaviourTest` is a [coroutine](https://docs.unity3d.com/ScriptReference/Coroutine.html) and a helper for writing MonoBehaviour tests.
  6. /// Yield a `MonoBehaviourTest` when using the `UnityTest` attribute to instantiate the `MonoBehaviour` you wish to test and wait for it to finish running. Implement the `IMonoBehaviourTest` interface on the `MonoBehaviour` to state when the test completes.
  7. /// </summary>
  8. /// <typeparam name="T">A MonoBehaviour component created for the test and attached to the tests [GameObject](https://docs.unity3d.com/ScriptReference/GameObject.html).</typeparam>
  9. public class MonoBehaviourTest<T> : CustomYieldInstruction where T : MonoBehaviour, IMonoBehaviourTest
  10. {
  11. /// <summary>
  12. /// A MonoBehaviour component created for the test and attached to the test's [GameObject](https://docs.unity3d.com/ScriptReference/GameObject.html).
  13. /// </summary>
  14. public T component { get; }
  15. /// <summary>
  16. /// A `GameObject` created as a container for the test component.
  17. /// </summary>
  18. public GameObject gameObject { get { return component.gameObject; } }
  19. /// <summary>
  20. /// Initializes and returns an instance of MonoBehaviourTest.
  21. /// </summary>
  22. /// <param name="dontDestroyOnLoad"></param>
  23. /// <example>
  24. /// <code>
  25. /// [UnityTest]
  26. /// public IEnumerator MonoBehaviourTest_Works()
  27. /// {
  28. /// yield return new MonoBehaviourTest&lt;MyMonoBehaviourTest&gt;();
  29. /// }
  30. ///
  31. /// public class MyMonoBehaviourTest : MonoBehaviour, IMonoBehaviourTest
  32. /// {
  33. /// private int frameCount;
  34. /// public bool IsTestFinished
  35. /// {
  36. /// get { return frameCount &gt; 10; }
  37. /// }
  38. ///
  39. /// void Update()
  40. /// {
  41. /// frameCount++;
  42. /// }
  43. /// }
  44. /// </code>
  45. /// </example>
  46. public MonoBehaviourTest(bool dontDestroyOnLoad = true)
  47. {
  48. var go = new GameObject("MonoBehaviourTest: " + typeof(T).FullName);
  49. component = go.AddComponent<T>();
  50. if (dontDestroyOnLoad)
  51. {
  52. Object.DontDestroyOnLoad(go);
  53. }
  54. }
  55. /// <summary>
  56. /// (Inherited) Returns `true`` if the test is not finished yet, which keeps the coroutine suspended
  57. /// </summary>
  58. public override bool keepWaiting
  59. {
  60. get { return !component.IsTestFinished; }
  61. }
  62. }
  63. }