Pester批量执行测试时出现HeaderInterceptor类型转换异常求助
Pester批量运行测试时出现PSInvalidCastException类型转换异常
在使用Pester时遇到如下问题:通过单条Invoke-Pester命令批量运行多个测试时,将继承自父类的测试类实例传递给接收父类类型参数的方法时,触发PSInvalidCastException异常。
示例代码
class TestInterceptor : HeaderInterceptor { [void] Intercept([ApiRequest]$Request) { .... # 使用测试数据重写 } } [void] AddClientHeaderInterceptor([HeaderInterceptor]$HeaderInterceptor) { .... } It 'Adds new host interceptor to all clients' { $interceptor = [TestInterceptor]::new() # 失败处 $testService.AddClientHeaderInterceptor($interceptor) }
错误信息
Cannot convert argument "HeaderInterceptor", with value: "HeaderInterceptor", for "AddClientHeaderInterceptor" to type "HeaderInterceptor": "Cannot convert the "HeaderInterceptor" value of type "HeaderInterceptor" to type "HeaderInterceptor"
测试场景差异
- 同一PowerShell会话中单独运行单个测试文件(
Invoke-Pester $testFile),测试可正常通过; - 使用
Invoke-Pester -configuration $config(默认配置)批量运行所有测试文件时,测试失败; - 手动逐个运行所有测试,全部可通过,无法手动复现批量运行时的问题。
环境变化
唯一的改动是在一个被多个测试文件导入的模块中添加了using module语句。
手动验证与调试结果
- 在单独的PowerShell会话中手动测试类型转换,可正常完成:
using module ApiClientCore class TestInterceptor : HeaderInterceptor { [void] Intercept([ApiRequest]$Request) { $Request.Headers['Foo'] = 'Bar' } } $t = [TestInterceptor]::new() [HeaderInterceptor]$t # 输出:TestInterceptor
- 调试发现类型加载异常:同一类型的实例来自不同版本的程序集,导致转换失败:
$t = [TestInterceptor]::New() $t.GetType().Assembly.FullName # 输出:PowerShell Class Assembly, Version=1.0.0.69, Culture=neutral, PublicKeyToken=null [HeaderInterceptor]::new().getType().Assembly.FullName # 输出:PowerShell Class Assembly, Version=1.0.0.71, Culture=neutral, PublicKeyToken=null [HeaderInterceptor]$t # 报错:InvalidArgument: Cannot convert the "TestInterceptor" value of type "TestInterceptor" to type "HeaderInterceptor".
内容的提问来源于stack exchange,提问作者maclu
相关产品推荐
相关产品推荐

