BenchmarkDotNet 遇到奇怪的解决方案结构时无法找到测试

BenchmarkDotNet Unable to find Tests when it faces weird solution structure

我遇到了 BenchmarkDotNet 的问题,我很难解决

这是我的项目结构:

- 
    | - Infrastructure
    |        |
    |        | - TestsBenchmark
    |        | - MyInfra.sln
    | - src
            | - Tests
            | - MyProduct.sln

TestsBenchmark 引用 Tests 并且只有这行代码:

BenchmarkSwitcher.FromAssembly(typeof(BasicTests).Assembly).RunAll();

但是当我通过 dotnet run -c Release 运行 它抛出

// Generate Exception: Unable to find Tests in ...\Infrastructure and its subfolders. Most probably the name of output exe is different than the name of the .(c/f)sproj

之前我的项目结构是这样的:

- 
    | - src
            | - Tests
            | - TestsBenchmark

一切正常

复制步骤(手动),它重新创建文件夹结构、项目、项目关系、解决方案和添加 nugets。 运行 它在一些空文件夹中的 powershell 中:

mkdir Infrastructure
mkdir src
cd src
dotnet new xunit -n Tests
cd Tests
dotnet add package BenchmarkDotNet
cd ..
cd ..
cd Infrastructure
dotnet new console -n TestsBenchmark
cd TestsBenchmark
dotnet add package BenchmarkDotNet
cd ..
dotnet new sln -n Repro
dotnet sln add .\TestsBenchmark\TestsBenchmark.csproj
dotnet sln add .\..\src\Tests\Tests.csproj
cd TestsBenchmark
dotnet add reference "..\..\src\Tests\Tests.csproj"

UnitTest1.cs

using System;
using BenchmarkDotNet.Attributes;
using Xunit;

namespace Tests
{
    public class UnitTest1
    {
        [Fact]
        [Benchmark]
        public void Test1()
        {
            Console.WriteLine("asd");
        }
    }
}

Program.cs

using System;
using BenchmarkDotNet.Running;
using Tests;

namespace TestsBenchmark
{
    class Program
    {
        static void Main(string[] args)
        {
            BenchmarkSwitcher.FromAssembly(typeof(UnitTest1).Assembly).RunAll();
        }
    }
}

现在在里面 Infrastructure\TestsBenchmark

执行dotnet run -c Release

你会看到

// Generate Exception: Unable to find Tests in C:\Infrastructure and its subfolders. Most probably the name of output exe is different than the name of the .(c/f)sproj

// BenchmarkDotNet has failed to build the auto-generated boilerplate code.
// It can be found in C:\repro\Infrastructure\TestsBenchmark\bin\Release\net5.0ba2c51-e794-4f44-93ab-f811411c86f5
// Please follow the troubleshooting guide: https://benchmarkdotnet.org/articles/guides/troubleshooting.html

简短的回答是您不能 运行 使用您创建的结构进行基准测试,这是故意的。

对于 BenchmarkDotNet(这通常是一个好的做法),解决方案需要具有以下结构

   | - root
             |
             | - Project1/Project1.csproj
             | - Project2/Project2.csproj
             | - Project3/Project3.csproj
             | - ProjectInsideFolder
                       | - Project4/Project4.csproj
             | - YouSolution.sln

所以你可以把项目放在子文件夹或者虚拟子文件夹,但是sln文件必须在根目录下。

BenchmarkDotNet 需要为您的测试项目找到 csproj 文件并为此使用以下算法

然后在所有子目录和根目录中搜索项目文件。

在 2 个或更多解决方案中使用同一项目的注意事项: 除非绝对必要,否则不要在 2 个不同的解决方案中使用同一个项目。它有它的后果,还有一个选项可以将它重用为 nuget-package you can create your own nuget feed for that.