[英]How to unit test this function?
I am trying to write unit testing for the following code:我正在尝试为以下代码编写单元测试:
This is my logic这是我的逻辑
public async Task RemoveUser(string id)
{
var response = await _graphQLClient.SendMutationAsync<Response>(request);
if (response.Errors != null)
{
throw new ClientException(errorMessages);
}
}
This is my unit testing这是我的单元测试
[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? */ );
}
I am confused with what should I compare my results?我很困惑我应该比较我的结果?
And how to handle:以及如何处理:
<System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult]
<System.Threading.Tasks.Task`1[System.Threading.Tasks.VoidTaskResult]
? ?
If you're using async Tasks in your unit test, it's best to make your test function a Task as well.如果您在单元测试中使用异步任务,最好将您的测试 function 也设置为任务。
Luckely the framework supports this.幸运的是,框架支持这一点。
Adding async
will give you the benifit of await
as well.添加
async
也会给你带来await
的好处。
public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
//...
await psClient.RemoveUser(id);
//nothing thrown, all okay --- not really the best test case
}
Normally you would assert some response:通常你会断言一些响应:
public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
//...
var result = await psClient.RemoveUser(id);
//Assert(result);
}
Or more integration style;或者更多的整合风格;
public async Task RemoveUser_ShouldCancelUserOnSucessfulRemoval()
{
//...
var removeResult = await psClient.RemoveUser(id);
var queryResult = await psClient.GetUser(id);
//assert user is gone
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.