2

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()
   ...
}


linuxias
  • 306
  • 2
  • 10
  • Make it async all the way. Your test methods can be asynchronous. `public async Task Test_GetDataAsync() { string res = await GetDAsync(); }` – Igor Apr 28 '22 at 18:31

1 Answers1

2

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());
}
Maytham Fahmi
  • 31,138
  • 14
  • 118
  • 137
  • The method I am testing is the GetData() method, which is not the async method. If you modify it in the way you recommended, the following error will occur. ``` 'string' does not contain a definition of 'GetAwaiter' and no accessible extension method 'GetAwaiter' accepting a first argument of type 'string' could be found (are you missing a using directive or assembly reference?) ``` ``` – linuxias Apr 29 '22 at 01:19
  • Check update answer – Maytham Fahmi Apr 29 '22 at 05:59
  • 1
    Thanks for your reply. My unity environment set .net version is 4.0. I will try more. – linuxias Apr 29 '22 at 07:03