How to refactor UnityTests - seperating methods with yield

Hello :slight_smile:

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):

[UnityTest]
public IEnumerator WaitFor1Second()
{
     float startTime = Time.time;
     yield return new WaitForSeconds(1f);
     Assert.AreEqual(1f, Time.time - startTime, 0.1f);
}

[UnityTest]
public IEnumerator WaitFor2Seconds()
{
     float startTime = Time.time;
     yield return new WaitForSeconds(2f);
     Assert.AreEqual(2f, Time.time - startTime, 0.1f);
}

How can I split those tests up? At the end it should look like this:

[UnityTest]
public IEnumerator WaitFor1Second()
{
     yield return WaitSecondsTest(1f);
}

[UnityTest]
public IEnumerator WaitFor2Seconds()
{
     yield return WaitSecondsTest(2f);
}

Thanks and have a great day!

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.

        [UnityTest]
        public IEnumerator TimerShouldSucceedAfter2Seconds()
        {
            float elapsed = 0f;
            float timer = 2f;

            while(!CustomTimer(timer, ref elapsed))
            {
                yield return null;
            }

            Assert.IsTrue(elapsed >= timer);
        }

        private bool CustomTimer(float time, ref float elapsed)
        {
            elapsed += Time.deltaTime;
            return elapsed >= time;
        }

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.

Hey Nigey!

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