Axe*_*lly 3 c# benchmarkdotnet
我在 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
一切正常
复制步骤(手动),它重新创建文件夹结构、项目、项目关系、解决方案并添加 nuget。在某个空文件夹中的例如 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"
单元测试1.cs
using System;
using BenchmarkDotNet.Attributes;
using Xunit;
namespace Tests
{
    public class UnitTest1
    {
        [Fact]
        [Benchmark]
        public void Test1()
        {
            Console.WriteLine("asd");
        }
    }
}
程序.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.0\65ba2c51-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,您可以为此创建自己的 nuget feed。