Failing a UnityTest when a condition that's expect to change in given amount of time doesn't?
I'm writing a UnityTest that waits for a condition to change before proceeding (i.e. while([condition]) yield return null
). Normally the condition will change after a few frames, but what if there's a bug system under test and the condition never changes. Here's an example:
[UnityTest]
public IEnumerator Test()
{
var fixture = new ClassUnderTest();
Assert.IsFalse(fixture.somethingIsDone));
fixture.DoSomethingLongishAsync();
// Normally the condition becomes true after a few frames
while (!fixture.somethingIsDone)
yield return null;
Assert.AreEqual("foobar", fixture.thingToTest);
}
Now if there was a bug in DoSomethingLongishAsync
method, and which results in somethingIsDone
never becoming true
, the test would run forever. What's a good way to prevent this and fail the test after a short time e.g. 1 second or 100 frames.
A real example I can think of is testing component that instructs a NavMeshAgent
to move to given destination. What if the agent cannot reach the destination? I suppose there are ways to detect this without having to wait, but in other cases, the only way to know if something has failed is to wait.
Answer by Hellium · Jul 03, 2020 at 08:09 PM
Disclaimer: I haven't tried it myself
[UnityTest]
public IEnumerator Test()
{
var stopWatch = System.Diagnostics.Stopwatch.StartNew();
var fixture = new ClassUnderTest();
Assert.IsFalse(fixture.somethingIsDone));
fixture.DoSomethingLongishAsync();
// Normally the condition becomes true after a few frames
while (!fixture.somethingIsDone && stopWatch.ElapsedMilliseconds < 1000)
yield return null;
Assert.AreEqual("foobar", fixture.thingToTest);
}
Your answer
Follow this Question
Related Questions
Checking Internet inside a Coroutine 0 Answers
Condition implementation Problem 1 Answer
Coroutine doesn't continue after yield another coroutine 0 Answers
Designing a dialogbox that displays message, returns a custom object and waits for user response 0 Answers
Question to WaitForEndOfFrame 2 Answers