首页 > 解决方案 > xUnit 无法输出到控制台 .NET

问题描述

尝试学习如何使用 xunit 在控制台中显示输出并苦苦挣扎。我正在使用VSCodedotnet test并在 VSCode 终端中运行测试。我也尝试过从 VSCode 之外的终端运行。

我还尝试在 VSCode 的代码窗口中运行高于测试功能的调试测试,但收到 OmniSharp 参数异常。

我创建了一个新的测试项目,dotnet new xunit并使用以下测试类和ITestOutputHelper.

using System;
using System.IO;
using System.Threading.Tasks;

using Xunit;
using Xunit.Abstractions;
using System.Text.Json;
using WebApp.Data;
using WebApp.UnitTests.Fixtures;


namespace WebApp.UnitTests
{
    [Collection("Motion collection")]
    public class MotionInfoTest
    {
        private const string MotionResourceFile = @"WebApp.UnitTests.TestData.motion.json";

        private MotionDetectionFixture _fixture;
        private ITestOutputHelper _output;

        public MotionInfoTest(MotionDetectionFixture fixture, ITestOutputHelper output) {
            _fixture = fixture;
            _output = output;
        }

        [Fact]
        // public async Task TestMotionInfo()
        public void TestMotionInfo()
        {
           try {
               Stream s = _fixture.GetStream(MotionResourceFile);
               
               _output.WriteLine(s.ReadTimeout.ToString());
               if(s is null) {
                   throw new Exception ("ArgumentException");
               }
               _output.WriteLine("Finished TestMotionInfo");
           }
           catch(Exception e) {
               _output.WriteLine("Exception occurred {0}", e.Message);
           }
            //MotionDetection obj = await JsonSerializer.DeserializeAsync<MotionDetection>(_fixture.GetStream(MotionResourceFile));

            Assert.Equal(1,1);
            //Assert.Equal("TensorFlow-WithFiltering-And-MQTT", obj.Plug);
        }
    }
}

创建的csproj文件dotnet new xunit是:

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <TargetFramework>netcoreapp3.1</TargetFramework>

    <IsPackable>false</IsPackable>
  </PropertyGroup>

  <ItemGroup>
    <PackageReference Include="Microsoft.NET.Test.Sdk" Version="16.5.0" />
    <PackageReference Include="xunit" Version="2.4.0" />
    <PackageReference Include="xunit.runner.visualstudio" Version="2.4.0" />
    <PackageReference Include="coverlet.collector" Version="1.2.0" />
  </ItemGroup>

  <ItemGroup>
    <ProjectReference Include="..\WebApp.Data\WebApp.Data.csproj" />
  </ItemGroup>

  <ItemGroup>
    <EmbeddedResource Include="TestData\*.json" />
  </ItemGroup>

</Project>

有没有人设法将输出显示到控制台?

标签: .net-corexunit.net

解决方案


如果我使用以下命令,则输出会出现在终端窗口和 VS Code 嵌入式终端中:

dotnet test --logger "console;verbosity=detailed"


推荐阅读