您好我正在使用Mono在c#中进行单元测试。我正在测试一个使用委托来返回Web服务响应的异步方法。 所以这是我的测试:
[Test]
public void TestCreateUser()
{
Debug.Log("TestCreateUser");
Vizzario.Instance.OnCreateUserSuccess += delegate(CreateUserResponse x)
{
Debug.Log("TestCreateUser: " + x.Response);
UnityEngine.Assertions.Assert.IsNotNull(x.TokenResponse.AuthToken);
UnityEngine.Assertions.Assert.AreEqual(BaseResponse.ResponseEnum.SUCCESS, x.Response);
// Signal that work is finished.
bool s = autoResetEvent.Set();
Debug.Log(s);
};
// Does the request
InitData.NewUserData.Email = InitData.GetRandomEmail();
Vizzario.Instance.CreateUser(InitData.NewUserData);
// Wait for work method to signal.
bool a = autoResetEvent.WaitOne(TimeSpan.FromSeconds(5), true);
Debug.Log(a);
}
因此,当我运行此测试时,WaitOne的结果在执行MyClass.Instance.OnCreateUserSuccess的主体之前执行,并且它打印为false。
所以它打印的内容如下:1。false,2。TestCreateUser:Success 什么时候应该打印如下:1。TestCreateUser:Success,2。true
为什么waitone不工作,我尝试增加autoResetEvent.WaitOne(TimeSpan.FromSeconds(5),true); to autoResetEvent.WaitOne(TimeSpan.FromSeconds(60),true);但我得到了相同的结果,我知道CreateUser方法不需要超过1或2秒,所以如果我尝试autoResetEvent.WaitOne();我的测试挂起,我必须重新启动ide。 有任何想法吗。 提前谢谢!
根据要求我添加了在我的vizzario类中调用的方法:
public delegate void CreateUserCallback(CreateUserResponse response);
public event CreateUserCallback OnCreateUserSuccess;
public event CreateUserCallback OnCreateUserError;
public void CreateUser(NewUserData data)
{
CreateUserResponse response = new CreateUserResponse();
this.DefApi.UserPost(data, ApiKey, ToolkitVersion, dryRun)
.Then(x =>
{
response.TokenResponse = x;
response.Response = BaseResponse.ResponseEnum.SUCCESS;
DoCreateUserNext(response);
})
.Catch(e =>
{
response.Response = BaseResponse.ResponseEnum.ERROR;
});
}
/// <summary>
/// Return callback in case of an exception inside the sdk.
/// </summary>
/// <param name="e"></param>
private void DoCreateUserError(Exception e)
{
if (OnCreateUserError != null)
{
CreateUserResponse response = new CreateUserResponse();
response.Response = BaseResponse.ResponseEnum.ERROR;
response.message = e.Message;
OnCreateUserError(response);
}
}
/// <summary>
/// Return callback from the sdk to the developer.
/// </summary>
/// <param name="response"></param>
private void DoCreateUserNext(CreateUserResponse response)
{
if (OnCreateUserSuccess != null)
{
if (response.Response == BaseResponse.ResponseEnum.SUCCESS)
{
OnCreateUserSuccess(response);
}
}
if (OnCreateUserError != null)
{
if (response.Response == BaseResponse.ResponseEnum.ERROR)
{
OnCreateUserError(response);
}
}
}