我正在尝试为以下代码编写单元测试:
这是我的逻辑
public async Task RemoveUser(string id)
{
var response = await _graphQLClient.SendMutationAsync<Response>(request);
if (response.Errors != null)
{
throw new ClientException(errorMessages);
}
}
这是我的单元测试
[Test]
public void RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
_mockGraphQLClient
.Setup(client => client.SendMutationAsync<object>(It.IsAny<GraphQLRequest>(), It.Is<CancellationToken>(token => token == default)))
.ReturnsAsync( new GraphQLResponse<object>());
var psClient = new PsClient(_mockGraphQLClient.Object);
var removeUserResults = psClient.RemoveUser(id);
Assert.AreEqual(removeUserResults, /* what to put here? */ );
}
我对应该比较结果的内容感到困惑?
以及如何处理:
<块引用>?
答案 0 :(得分:2)
如果您在单元测试中使用异步任务,最好也将您的测试功能设为任务。
幸运的是框架支持这一点。
添加 async
也会给您带来 await
的好处。
public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
//...
await psClient.RemoveUser(id);
//nothing thrown, all okay --- not really the best test case
}
通常你会断言一些响应:
public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
//...
var result = await psClient.RemoveUser(id);
//Assert(result);
}
或者更多的集成风格;
public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
//...
var removeResult = await psClient.RemoveUser(id);
var queryResult = await psClient.GetUser(id);
//assert user is gone
}