Wayback Machinekoobas.hobune.stream
May JUN Jul
Previous capture 14 Next capture
2021 2022 2023
2 captures
12 Jun 22 - 14 Jun 22
sparklines
Close Help
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
  • Asset Store
  • Get Unity

UNITY ACCOUNT

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account
  • Blog
  • Forums
  • Answers
  • Evangelists
  • User Groups
  • Beta Program
  • Advisory Panel

Navigation

  • Home
  • Products
  • Solutions
  • Made with Unity
  • Learning
  • Support & Services
  • Community
    • Blog
    • Forums
    • Answers
    • Evangelists
    • User Groups
    • Beta Program
    • Advisory Panel

Unity account

You need a Unity Account to shop in the Online and Asset Stores, participate in the Unity Community and manage your license portfolio. Login Create account

Language

  • Chinese
  • Spanish
  • Japanese
  • Korean
  • Portuguese
  • Ask a question
  • Spaces
    • Default
    • Help Room
    • META
    • Moderators
    • Topics
    • Questions
    • Users
    • Badges
  • Home /
avatar image
1
Question by MathijsF · Feb 01, 2019 at 02:39 PM · testingasync

Async unit test in Test Runner

Is it possible to unit test async functions? I can't get it to work.

If I use 'async void', the test always passes, even if the assertion fails. If I use 'async Task', I can't run the test. Unity Test Runner reports: "Method has non-void return value, but no result is expected".

 [Test]
 public async void MyTestFailAsyncVoid()
 {
     await Task.Delay(1000);
     Assert.That(false);
 }
 
 [Test]
 public async Task MyTestFailAsyncTask()
 {
     await Task.Delay(1000);
     Assert.That(false);
 }

Comment
Add comment
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

3 Replies

· Add your reply
  • Sort: 
avatar image
4
Best Answer

Answer by MathijsF · May 28, 2019 at 10:06 AM

In case anybody else cares about this, we found a workaround of sorts.

It uses the 'Async Await Support' library on the Unity Store: link . We added a function to the library to have AsIEnumerator() return null:

 public static IEnumerator AsIEnumeratorReturnNull<T>(this Task<T> task)
 {
     while (!task.IsCompleted)
     {
         yield return null;
     }
 
     if (task.IsFaulted)
     {
         ExceptionDispatchInfo.Capture(task.Exception).Throw();
     }
 
     yield return null;
 }

An async test looks like this:

 [UnityTest]
 public IEnumerator MyAsyncTest()
 {
     var task = MyObject.SomeAsyncCall();
     yield return task.AsIEnumeratorReturnNull();
 
     var returnValue = task.Result;
     Assert.AreEqual(expectedReturnValue, returnValue);
 }

An async test that should throw an exception looks like this:

 [UnityTest]
 public IEnumerator MyAsyncTestThatShouldThrow()
 {
     async Task<bool> FailsWithException()
     {
         try
         {
             await MyObject.SomeAsyncCall();
         }
         catch (Exception)
         {
             return true;
         }
 
         return false;
     }
 
     var task = FailsWithException();
     yield return task.AsIEnumerator();
     
     var threwException = task.Result;
 
     Assert.That(threwException);
 }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by AlexStark_ · Jul 02, 2020 at 07:52 AM

Based on this thread https://forum.unity.com/threads/async-await-in-unittests.513857/#post-6046400 You can use the following helpers

     public static class UnityTestUtils {
  
         public static T RunAsyncMethodSync<T>(Func<Task<T>> asyncFunc) {
             return Task.Run(async () => await asyncFunc()).GetAwaiter().GetResult();
         }
         public static void RunAsyncMethodSync(Func<Task> asyncFunc) {
             Task.Run(async () => await asyncFunc()).GetAwaiter().GetResult();
         }
 }

Usage:

     [Test]
     public void Test()
     {
         var result = RunAsyncMethodSync(() => GetTestTaskAsync(4));
         Assert.That(result, Is.EqualTo(4));
     }
 
     public async Task<int> GetTestTaskAsync(int a) {
         await Task.Delay(TimeSpan.FromMilliseconds(200));
         return a;
     }
 
     [Test]
     public void Testthrow() {
         Assert.Throws<InvalidOperationException>(
                        ()=> RunAsyncMethodSync(() => ThrowTaskAsync(4)));
     }
 
     public async Task<int> ThrowTaskAsync(int a) {
         await Task.Delay(TimeSpan.FromMilliseconds(200));
         throw new InvalidOperationException();
     }
Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users
avatar image
0

Answer by ochir_d · May 25, 2021 at 12:37 AM

Utils

    public static class UnityTestUtils {
      public static void RunAsyncMethodSync(this Func < Task > asyncFunc) {
        Task.Run(async () => await asyncFunc()).GetAwaiter().GetResult();
      }
    }

Usage

 public class AsyncAwaitUnitTests {
      [Test]
      public void WithExt([Values(0, 500, 1000)] int delay) {
        UnityTestUtils.RunAsyncMethodSync(async () => {
          var sw = Stopwatch.StartNew();
 
          await Task.Delay(delay);
 
          Assert.AreEqual(delay, (int) sw.Elapsed.TotalMilliseconds, 300);
        });
      }
    }


Comment
Add comment · Share
10 |3000 characters needed characters left characters exceeded
▼
  • Viewable by all users
  • Viewable by moderators
  • Viewable by moderators and the original poster
  • Advanced visibility
Viewable by all users

Your answer

Hint: You can notify a user about this post by typing @username

Up to 2 attachments (including images) can be used with a maximum of 524.3 kB each and 1.0 MB total.

Follow this Question

Answers Answers and Comments

99 People are following this question.

avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image avatar image

Related Questions

Change the maximum length of a method name in the Test Runner Editor 0 Answers

Anyone tried Firebase Testlab for testing your game? 1 Answer

LoadLevel Async 2 Answers

Windows 8 - Windows.Storage WriteTextAsync exception 0 Answers

Additively loaded scene gets stuck at 90% even if allowSceneActivation is true. 2 Answers


Enterprise
Social Q&A

Social
Subscribe on YouTube social-youtube Follow on LinkedIn social-linkedin Follow on Twitter social-twitter Follow on Facebook social-facebook Follow on Instagram social-instagram

Footer

  • Purchase
    • Products
    • Subscription
    • Asset Store
    • Unity Gear
    • Resellers
  • Education
    • Students
    • Educators
    • Certification
    • Learn
    • Center of Excellence
  • Download
    • Unity
    • Beta Program
  • Unity Labs
    • Labs
    • Publications
  • Resources
    • Learn platform
    • Community
    • Documentation
    • Unity QA
    • FAQ
    • Services Status
    • Connect
  • About Unity
    • About Us
    • Blog
    • Events
    • Careers
    • Contact
    • Press
    • Partners
    • Affiliates
    • Security
Copyright © 2020 Unity Technologies
  • Legal
  • Privacy Policy
  • Cookies
  • Do Not Sell My Personal Information
  • Cookies Settings
"Unity", Unity logos, and other Unity trademarks are trademarks or registered trademarks of Unity Technologies or its affiliates in the U.S. and elsewhere (more info here). Other names or brands are trademarks of their respective owners.
  • Anonymous
  • Sign in
  • Create
  • Ask a question
  • Spaces
  • Default
  • Help Room
  • META
  • Moderators
  • Explore
  • Topics
  • Questions
  • Users
  • Badges