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 提要。
推荐阅读
- python - 使用 Python requests.put 函数上传文件被拒绝并出现错误 400
- django - django-plotly-dash,base.html 中的“第 0 行预期字符串或类似字节对象的错误”?
- python - 为什么python在if中从else写代码?
- android - Flutter 取消一系列本地通知
- javascript - 使用 json_encode 将数据从 Laravel 传递到 Vue 不起作用
- android - Android Studio 隐式意图基本问题
- mysql - 我正在尝试在单个列中为一个实体类制作两个不同的表多对一映射
- django - Django orm 从外来对象获取其他外键对象
- javascript - 当我们从一个页面返回到放置脚本的页面时,脚本没有加载
- python - 具有资源约束的多处理