你能测试一个函数是否真正异步运行吗?

问题描述 投票:0回答:1

我正在开发一个 ASP.NET Web Api 项目来学习框架及其测试,我想知道您是否可以测试异步方法实际上是异步运行的(或者它们是否由于任何错误而同步运行) .

    public class RepositoryBase<Tentity, Tcontext> : IRepositoryBase<Tentity> where Tentity : class where Tcontext : DbContext
    {
        protected Tcontext _RepositoryContext;
        protected DbSet<Tentity> dbSet;
        public RepositoryBase(Tcontext context)
        {
            this._RepositoryContext = context;
            dbSet = _RepositoryContext.Set<Tentity>();
        }
        public async Task Create(Tentity entity)
        {
            await dbSet.AddAsync(entity);
        }
    }

你能测试一下Create方法是否真正异步运行吗? 测试一个方法是否异步运行是否符合逻辑?或者这是一个微不足道的问题,因为它返回一个任务这一事实证明它是异步运行的。

在单元测试期间,在我的测试功能中,我只尝试了

await repository.Create(testUser);
,然后断言数据库内的用户和我输入的用户在各个方面都是相同的。但这只是测试 Create 函数的最终功能,而不是测试它是否成功异步运行。

c# asp.net unit-testing asynchronous testing
1个回答
-1
投票

你可以测试一下

Create
方法是否真正异步运行吗?

是的。您可以测试该方法是否返回尚未

completed
Task。而不是:

await repository.Create(testUser);

...这样做:

Task task = repository.Create(testUser);
Debug.Assert(!task.IsCompleted);
await task;
© www.soinside.com 2019 - 2024. All rights reserved.