I'm currently developing a game in Unity 2019 and C# and I use a lot of events and coroutines for it. The coroutines are necessary because many calculations are done in them and I don't want the game to freeze during that time. Now I started to write unit tests using the Test Runner (Play Mode) and the coroutines are just not executed. Since I really need to be sure that they work as expected, it's not possible to just test "on the higher level".
I already tried the normal StartCoroutine() method, which doesn't work in the test file ("method name not found"). Moreover, I refactored one of my coroutines to be a normal void method and everything worked well and it passed the test. I used the Visual Studio debugger to see if it jumps into the coroutine execution and it does not. So the problem clearly is, that the coroutines are not executed. I thought about moving the calculation logic to another void function and test this function (and leave out the coroutine), but I must be sure that the iterations done in the coroutine work as well (they usually are more complicated than in the example).
This is a minimal example showing the general structure (there are usually many more computations done).
public class MeasuredValues
{
List<Vector3> slidingWindow; // this is already filled when Normalize() is executed
public IEnumerator Normalize()
{
//find coordinate system origin
Vector3 originPosition = GetOrigin(); // returns a Vector3
//normalization
for (int i = 0; i < slidingWindow.Count; i++)
{
yield return null;
//reset point to be at (0,y,0)
slidingWindow[i] -= originPosition;
}
}
}
In the test file I want to:
[Test]
public void TestNormalization()
{
MeasuredValues myMeasuredValues = new MeasuredValues();
// add many Vector3 to slidingWindow
// call coroutine
// assert, that the values are now as expected
}
I tried myMeasuredValues.Normalize()
(didn't work, the debugger just jumped over it) and StartCoroutine(myMeasuredValues.Normalize)
(didn't work, the StartCoroutine is not available in that context).
Finally, I tried
while (test.Normalize().MoveNext())
{
yield return null;
}
but this never ends since the MoveNext()
is never set to false. At least the debugger jumped into the coroutine method.
Is there any easily applicable solution to test my coroutines with Visual Studio or Unity Test Runner without the need to refactor the whole project structure?