我创建了一个ASP.NET项目,并为它编写了一些集成测试。但是当我试图运行dotnet test
时,出现了以下情况:
Starting test execution, please wait...
A total of 1 test files matched the specified pattern.
The active test run was aborted. Reason: Test host process crashed : Unknown command: --environment=Development
Test Run Aborted with error System.Exception: One or more errors occurred.
---> System.Exception: Unable to read beyond the end of the stream.
at System.IO.BinaryReader.Read7BitEncodedInt()
at System.IO.BinaryReader.ReadString()
at Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.LengthPrefixCommunicationChannel.NotifyDataAvailable()
at Microsoft.VisualStudio.TestPlatform.CommunicationUtilities.TcpClientExtensions.MessageLoopAsync(TcpClient client, ICommunicationChannel channel, Action`1 errorHandler, CancellationToken cancellationToken)
--- End of inner exception stack trace ---.
据我所知,有些东西试图用--environment=Development
运行dotnet可执行文件,但此参数无效,即使它在Microsoft docs中使用。
我试着创建新的ASP.NET项目(没有控制器、服务、数据库等,只有API,什么都不做,测试也是空的),但我无法再次重现错误。
一开始,我无意中在同一个文件夹中创建了项目和解决方案,不得不手动将项目移到子文件夹中。这样做之后,一切都运行正常,所以我认为一切都很好。也许这就是原因。
下面是我在测试期间访问应用程序的方法:
// TestingApplication.cs
public class TestingApplication : WebApplicationFactory<Program>
{
private readonly Guid _appId = Guid.NewGuid();
protected override void ConfigureWebHost(IWebHostBuilder builder)
{
// Add mock/test services to the builder here
builder.ConfigureServices(services =>
{
services.AddMvcCore().AddApplicationPart(typeof(Program).Assembly);
services.AddScoped(sp => new DbContextOptionsBuilder<EfDbContext>()
.UseSqlServer(
$"DATABASE CONNECTION STRING")
.UseApplicationServiceProvider(sp)
.Options);
});
}
protected override IHost CreateHost(IHostBuilder builder)
{
var host = base.CreateHost(builder);
using (var serviceScope = host.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<EfDbContext>();
context.Database.EnsureCreated();
}
return host;
}
protected override void Dispose(bool disposing)
{
base.Dispose(disposing);
using (var serviceScope = Server.Services.GetRequiredService<IServiceScopeFactory>().CreateScope())
{
var context = serviceScope.ServiceProvider.GetRequiredService<EfDbContext>();
context.Database.EnsureDeleted();
}
}
}
// BaseTest.cs
public class BaseTest : IDisposable, IClassFixture<TestingApplication>
{
protected readonly TestingApplication Application;
private HttpClient? _client;
protected HttpClient Client => _client ??= Application.CreateClient();
public BaseTest(TestingApplication testingApplication)
{
Application = testingApplication;
}
public void Dispose()
{
Application.Dispose();
}
}
更多信息:
- 单元测试工作正常
- 最初我忘记将
<InternalsVisibleTo Include="NameOfTestsProject" />
添加到主项目文件中,但无论哪种方法都不起作用。 - . NET 6,操作系统-Linux,集成开发环境-Jetbrains骑士
- 重建解决方案不起作用
- 为单元测试创建新项目也没有帮助
有人知道问题出在哪里吗?
"UPD"我想明白了
1条答案
按热度按时间2wnc66cl1#
好的,这只是另一个复制粘贴别人代码而不检查的例子。我复制了一些代码,大致如下:
在我的Programidocs中。它本身工作得很好,但在测试时却导致了这个问题。