<PackageReference Include="NUnit" Version="4.5.0" />

TextCapture

public class TextCapture : TextWriter
The TextCapture class intercepts console output and writes it to the current execution context, unless it corresponds with an ad-hoc test context. In an ad-hoc context, the output is written to a default destination, normally the original destination of the intercepted output.
using System.IO; using System.Runtime.CompilerServices; using System.Text; namespace NUnit.Framework.Internal.Execution { [System.Runtime.CompilerServices.NullableContext(1)] [System.Runtime.CompilerServices.Nullable(0)] public class TextCapture : TextWriter { private readonly TextWriter _defaultWriter; public override Encoding Encoding => _defaultWriter.Encoding; public TextCapture(TextWriter defaultWriter) { _defaultWriter = defaultWriter; } public override void Write(char value) { GetWriter().Write(value); } [System.Runtime.CompilerServices.NullableContext(2)] public override void Write(string value) { GetWriter().Write(value); } [System.Runtime.CompilerServices.NullableContext(2)] public override void WriteLine(string value) { GetWriter().WriteLine(value); } private TextWriter GetWriter() { TestExecutionContext currentContext = TestExecutionContext.CurrentContext; if (!(currentContext is TestExecutionContext.AdhocContext) && currentContext.CurrentResult != null) return currentContext.CurrentResult.OutWriter; return _defaultWriter; } } }