【问题标题】:Test Case is finished before Thread execution is completed C#测试用例在线程执行完成之前完成 C#
【发布时间】:2020-11-02 19:57:28
【问题描述】:

环境: 点网核心:3.1, 单元:3.12.0


我试图为一个将创建重量级孤立线程的类中的公共方法编写单元测试,当我试图在我的应用程序孤立线程中运行所有单元测试用例时,孤立线程没有正确执行并且它正在终止在中间,由于其他单元测试用例没有执行。下面是它抛出的错误。

A total of 1 test files matched the specified pattern. The active test run was aborted. Reason: Test host process crashed

Code Snippet
// Unit test case logic
[Test(Description = "TestCase. - orphan Thread)]
public async Task OrphanThreadUntiTestCase()
{
     var actual = _repository.SampleMethod();
     Assert.AreEqual(true, actual.Result);

}


// Repository Logic
public class Repository{
constructor(){
}
public SampleMethod(){
 _ = Task.Run(() =>
  {
       HeavyTask();
  });

return true;
}

private HeavyTask(){
// execution of this task was taking more time.
// due to this Task my whole unit test cases are not executed.
}

}

【问题讨论】:

    标签: c# multithreading unit-testing .net-core nunit


    【解决方案1】:

    SampleMethod 所做的是“一劳永逸”任务。您应该将方法更改为异步:

    public async Task SampleMethod()
    {
      return Task.Run(() =>
        {
           HeavyTask();
        });
    }
    

    然后在OrphanThreadUntiTestCase中等待这个方法:

    await SampleMethod();
    

    【讨论】:

      猜你喜欢
      • 2021-11-15
      • 1970-01-01
      • 1970-01-01
      • 2016-09-12
      • 1970-01-01
      • 1970-01-01
      • 2019-11-16
      • 2020-10-02
      • 1970-01-01
      相关资源
      最近更新 更多