【发布时间】:2020-11-22 01:23:50
【问题描述】:
我是 Unity 的新手,发现它的异步管理有点难以处理,所以我使用 IPromises : https://github.com/Real-Serious-Games/C-Sharp-Promise 这让我可以使用
MyAsyncFunction.Then(() =>
{
// What happened if everything went OK
}).Catch(error =>
{
// What happend if an exception was thrown
})
我也在使用 Unity Rest Client,它使用IPromises:https://github.com/proyecto26/RestClient
我正在使用 NUnit 进行测试,似乎 它必须在测试异步代码时返回一个任务。
在我的代码中,我使用 Unity Rest Client 并将我的 Assert 放在 Then 部分中。问题是 NUnit 不等待请求,因此不执行断言。
这是我的代码:
[Test]
public async Task TestLogin()
{
_network.SendCode(_password)
.Then(authResp =>
{
Assert.True(authResp.IsSuccessful);
Assert.IsNotNull(authResp.Name);
Assert.IsNotNull(authResp.Surname);
Assert.IsNotNull(authResp.AccessToken);
Assert.AreEqual(authResp.AccessToken, _tokenStorage.RetrieveAccessToken());
});
}
这里是SendCode的实现:
public IPromise<AuthenticationResponse> SendCode(string code)
{
var promise = new Promise<AuthenticationResponse>();
RestClient.Post("/api/login", new Credentials(code))
.Then(response =>
{
EditorUtility.DisplayDialog("JSON", JsonUtility.ToJson(response, true), "Ok");
promise.Resolve(new AuthenticationResponse("", "", true, "", "200"));
})
.Catch(error =>
{
EditorUtility.DisplayDialog("ERROR", JsonUtility.ToJson(error, true), "Ok");
promise.Reject(new Exception("Error when logging"));
});
return promise;
}
我看到了两种可能性:
- 在测试中将
IPromise转换为Task - 更改
SendCode的实现,使其返回Task。并放弃使用 UnityRestClient :'(
如果有人知道如何做第一种可能性,或者能给我一点指导来做第二种可能性,那就太棒了。
【问题讨论】:
-
你是如何运行测试的?在 Unity Test Runner 中或以其他方式。您使用的是哪个版本的 Unity?
标签: c# .net unity3d asynchronous testing