Home > other >  How to test method include async method in Unity
How to test method include async method in Unity

Time:04-29

I want to test method using async method. But, when i run test, UnityEditor is blocking.

I think, this problem is because async method. i don't know how to solve this problem.

Unity version : Unity 2020.3.33f1

public async static Task<string> GetAsync() {

    // Do something
    HttpResponseMessage response = await request.GetAsync(..);
    string responseData = await response.Content.ReadAsStringAsync();


    return response Data
}

...


public string GetData() {
    Task<string> res = GetAsync();
    return res.Result;
}


////////////////// Test Code //////////////

[Test]
public void Test_GetData() {
   ...
   string res = GetData()
   ...
}


CodePudding user response:

Without testing it, you need to use async/await in all places.

When using async/await, as you have done Task for returning string type, but for void method, you just use Task.

let's say

public static async Task<string> GetAsync()
{
    return await Task.FromResult("test");
}

and your test should be like this:

[Test]
public async Task Test_GetAsync()
{
    var result = await GetAsync();
    Assert.AreEqual("test", result);
}

if we take your code so

public async static Task<string> GetAsync() {
    // what ever
    .....
    return responseData
}

the test will be:

[Test]
public async Task Test_GetData() {
   ...
   string res = await GetData()
   ...
}

If your test project is an older .net framework, you would level it up to a newer version as this answer suggests. Otherwise, if you are locked and not able to upgrade, you can do something which I am not suggesting as this answer mentions.

[Test]
public void Test_GetData()
{
    var result = GetAsync().GetAwaiter();
    Assert.AreEqual("test", result.GetResult());
}
  • Related