I'm new to Unity and found its asynchronous management a little bit difficult to handle, so I'm using IPromises
: https://github.com/Real-Serious-Games/C-Sharp-Promise which allows me to use
MyAsyncFunction.Then(() =>
{
// What happened if everything went OK
}).Catch(error =>
{
// What happend if an exception was thrown
})
I'm also using Unity Rest Client, which uses IPromises
: https://github.com/proyecto26/RestClient
I'm using NUnit for testing and it seems it has to return a Task when testing async code.
In my code, I use the Unity Rest Client and put my Assert
's in the Then
part. The problem is that NUnit doesn't wait for the request and thus does not perform the assertions.
Here is my code:
[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());
});
}
And here is the implementation of 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;
}
I see 2 possibilities:
- Transforming the
IPromise
to aTask
in the test - Changing the implementation of
SendCode
so that it returns aTask
. And renounce to use the UnityRestClient :'(
If anyone know how to do the first possibility or can give me a little bit of guidance to do the second one, it would be amazing.
Aucun commentaire:
Enregistrer un commentaire