Search Unity

Support for async / await in tests

Discussion in 'Testing & Automation' started by liortal, Dec 3, 2019.

  1. liortal

    liortal

    Joined:
    Oct 17, 2012
    Posts:
    3,335
    Does the Unity test framework support running test methods that are marked as 'async' (e.g: using the await keyword) ?

    This test is shown in the test runner (but doesn't properly work since the test exits without waiting for the task to complete):
    Code (CSharp):
    1. [Test]
    2. public async void ThisTestSucceeds()
    3. {
    4.     await Task.Delay(5500);
    5.  
    6.     Assert.IsTrue(false);
    7. }
     
    NHals likes this.
  2. Warnecke

    Warnecke

    Unity Technologies

    Joined:
    Nov 28, 2017
    Posts:
    53
    Currently that is not supported. It might be possible when we upgrade the nunit version, but we do not have a timeframe for that yet.
     
  3. HugoClip

    HugoClip

    Joined:
    Feb 28, 2018
    Posts:
    38
    @Warnecke could you satisfy my curiosity and inform me why is that not a priority? Not being able to unit test async/await paths really limits the scope of what you can test, specially with recent libs.
     
  4. M_R

    M_R

    Joined:
    Apr 15, 2015
    Posts:
    528
    workaround:
    Code (CSharp):
    1.  public static IEnumerator AsCoroutine (this Task task)
    2.         {
    3.             while (!task.IsCompleted) yield return null;
    4.             // if task is faulted, throws the exception
    5.             task.GetAwaiter ().GetResult ();
    6.         }
    then use IEnumerator-based tests
    Code (CSharp):
    1. [UnityTest] public IEnumerator Test() {
    2.     yield return Run().AsCoroutine();
    3.     async Task Run() {
    4.         actual test code...
    5.     }
    6. }