You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Azure Pipeline执行dotnet test报错:无法读取流的末尾

在Azure Pipeline中运行dotnet test时出现"Unable to read beyond the end of the stream"错误的解决方法

问题描述

在Azure Pipeline执行dotnet test时,流水线失败并抛出以下错误:

System.Exception: Unable to read beyond the end of the stream.
   at System.IO.BinaryReader.Read7BitEncodedInt()
   at System.IO.BinaryReader.ReadString()
   at Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.LengthPrefixCommunicationChannel.NotifyDataAvailable()
   at Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.TcpClientExtensions.MessageLoopAsync(TcpClient client, ICommunicationChannel channel, Action`1 errorHandler, CancellationToken cancellationToken)
   --- End of inner exception stack trace ---.
##[error]Error: The process '/opt/hostedtoolcache/dotnet/dotnet' failed with exit code 1

根据分析,该错误的核心原因是:测试代码直接终止了testhost进程,而非等待vstest.console正常通知退出,导致vstest.console判定测试进程崩溃,进而触发流读取异常。

解决方案

1. 排查并修改测试中的强制终止逻辑

检查所有测试用例,确认是否存在Environment.Exit()、Process.Kill()等直接终止当前进程的代码。这类操作会直接杀死testhost,中断与vstest.console的通信。
将此类逻辑替换为符合测试框架规范的方式:

  • xUnit中使用Assert.Fail()标记测试失败
  • NUnit中使用Assert.Fail()或抛出预期内的异常
  • 让测试正常执行结束,避免强制退出

2. 启用测试进程隔离

通过.runsettings配置文件,强制每个测试程序集在独立进程中运行,避免单个测试崩溃影响整个testhost:
创建test.runsettings文件,内容如下:

<RunSettings>
  <RunConfiguration>
    <UseSeparateProcessPerTestAssembly>true</UseSeparateProcessPerTestAssembly>
    <TestHostProcessTimeout>300000</TestHostProcessTimeout>
  </RunConfiguration>
</RunSettings>

在Azure Pipeline的dotnet test任务中引用该配置:

- task: DotNetCoreCLI@2
  inputs:
    command: 'test'
    projects: '**/*Tests.csproj'
    arguments: '--settings test.runsettings'

3. 更新测试平台依赖包

确保项目中以下包使用最新稳定版本:

  • Microsoft.NET.Test.Sdk
  • 对应测试框架的适配器包(如xunit.runner.visualstudio、nunit3.testadapter)
    旧版本可能存在通信逻辑bug,更新后可修复部分异常场景。

4. 处理测试中的未捕获异常

确保测试代码中所有可能抛出异常的逻辑都被合理捕获,未处理的异常会导致testhost意外崩溃。在测试方法中添加try-catch块,或配置测试框架的全局异常处理机制。

内容的提问来源于stack exchange,提问作者iarunpaul

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.28 18:05:10