@@ -955,4 +955,50 @@ i -PassThru:$PassThru {
955955 $xmlResult.Validate ({ throw $args [1 ].Exception })
956956 }
957957 }
958+
959+ # Regression test for https://github.com/pester/Pester/issues/2649
960+ # When a test outputs an object whose ToString() throws, the NUnit3 report
961+ # writer (Format-CDataString) would crash, losing the entire report.
962+ # The fix wraps ToString() in try/catch and uses a fallback string.
963+ b " NUnit3 report handles objects with broken ToString()" {
964+ t " should produce valid report when test output object throws on ToString" {
965+ # Create a class whose ToString() throws
966+ $typeAdded = try { [BrokenToString ] } catch { $false }
967+ if (-not $typeAdded ) {
968+ Add-Type - TypeDefinition '
969+ public class BrokenToString {
970+ public override string ToString() {
971+ throw new System.InvalidOperationException("ToString failed");
972+ }
973+ }
974+ '
975+ }
976+
977+ $sb = {
978+ Describe ' Describe' {
979+ It ' Outputs broken object' {
980+ # Output an object whose ToString() will throw
981+ [BrokenToString ]::new()
982+ $true | Should - Be $true
983+ }
984+ }
985+ }
986+
987+ $r = Invoke-Pester - Configuration ([PesterConfiguration ]@ {
988+ Run = @ { ScriptBlock = $sb ; PassThru = $true }
989+ Output = @ { Verbosity = ' None' }
990+ })
991+
992+ # The test itself should pass
993+ $r.Result | Verify- Equal ' Passed'
994+
995+ # Converting to NUnit3 report should NOT throw
996+ $xmlResult = $r | ConvertTo-NUnitReport - Format NUnit3
997+
998+ # The output section should contain the fallback message
999+ $xmlTest = $xmlResult .' test-run' .' test-suite' .' test-suite' .' test-case'
1000+ $xmlTest.result | Verify- Equal ' Passed'
1001+ $xmlTest.output .' #cdata-section' | Verify- Like ' *ToString() failed*'
1002+ }
1003+ }
9581004}
0 commit comments