Search Unity

  1. Megacity Metro Demo now available. Download now.
    Dismiss Notice
  2. Unity support for visionOS is now available. Learn more in our blog post.
    Dismiss Notice

How to refactor UnityTests - seperating methods with yield

Discussion in 'Scripting' started by Zwer99, Apr 5, 2018.

  1. Zwer99

    Zwer99

    Joined:
    Oct 24, 2013
    Posts:
    24
    Hello :)

    I wonder how to seperate methods which return IEnumerator with yield. For example I have the following nearly identical tests (it doens't matter if the tests make sense):

    Code (CSharp):
    1. [UnityTest]
    2. public IEnumerator WaitFor1Second()
    3. {
    4.      float startTime = Time.time;
    5.      yield return new WaitForSeconds(1f);
    6.      Assert.AreEqual(1f, Time.time - startTime, 0.1f);
    7. }
    8.  
    9. [UnityTest]
    10. public IEnumerator WaitFor2Seconds()
    11. {
    12.      float startTime = Time.time;
    13.      yield return new WaitForSeconds(2f);
    14.      Assert.AreEqual(2f, Time.time - startTime, 0.1f);
    15. }
    How can I split those tests up? At the end it should look like this:

    Code (CSharp):
    1. [UnityTest]
    2. public IEnumerator WaitFor1Second()
    3. {
    4.      yield return WaitSecondsTest(1f);
    5. }
    6.  
    7. [UnityTest]
    8. public IEnumerator WaitFor2Seconds()
    9. {
    10.      yield return WaitSecondsTest(2f);
    11. }
    Thanks and have a great day!
     
  2. Nigey

    Nigey

    Joined:
    Sep 29, 2013
    Posts:
    1,129
    Last time I checked for UnityTest you can only yield null, you can't yield any IEnumerators or new WaitForSeconds(f). You'd probably need to do something alone the lines of:

    Untested.
    Code (CSharp):
    1.         [UnityTest]
    2.         public IEnumerator TimerShouldSucceedAfter2Seconds()
    3.         {
    4.             float elapsed = 0f;
    5.             float timer = 2f;
    6.  
    7.             while(!CustomTimer(timer, ref elapsed))
    8.             {
    9.                 yield return null;
    10.             }
    11.  
    12.             Assert.IsTrue(elapsed >= timer);
    13.         }
    14.  
    15.         private bool CustomTimer(float time, ref float elapsed)
    16.         {
    17.             elapsed += Time.deltaTime;
    18.             return elapsed >= time;
    19.         }
    As part of the 3 A's. I'd consider the floats the arrange, the method the act, and so I would (for me) separate the assert outside of the method below the while statement.
     
    Last edited: Apr 5, 2018
  3. Zwer99

    Zwer99

    Joined:
    Oct 24, 2013
    Posts:
    24
    Hey Nigey!

    Thanks for your suggestion - I think I can work with that ^^