EF Core 2.1集成测试中的延迟加载

时间:2018-10-22 08:50:17

标签: asp.net-core entity-framework-core integration-testing automapper lazy-loading

我花了几天的时间对此进行黑客攻击,但并不高兴。

我有一个通过代理方法启用了延迟加载的项目。该应用程序在运行时按预期运行。但是,当我运行集成测试套件时,在测试中会出现随机错误,并显示以下错误。

Message: System.Reflection.ReflectionTypeLoadException : Unable to load one or more of the requested types.
Could not load type 'Castle.Proxies.ChangeLogProxy' from assembly 'DynamicProxyGenAssembly2, Version=0.0.0.0, Culture=neutral, PublicKeyToken=null'.

这是堆栈跟踪

Result StackTrace:  
at System.Reflection.RuntimeModule.GetTypes(RuntimeModule module)
   at System.Reflection.RuntimeAssembly.get_DefinedTypes()
   at System.Linq.Enumerable.SelectManySingleSelectorIterator`2.ToArray()
   at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
   at AutoMapper.ServiceCollectionExtensions.AddAutoMapperClasses(IServiceCollection services, Action`1 additionalInitAction, IEnumerable`1 assembliesToScan) in C:\projects\automapper-extensions-microsoft-dependencyinjectio\src\AutoMapper.Extensions.Microsoft.DependencyInjection\ServiceCollectionExtensions.cs:line 69
   at Web.Startup.ConfigureServices(IServiceCollection services) in C:\...\src\Web\Startup.cs:line 39
--- End of stack trace from previous location where exception was thrown ---
   at Microsoft.AspNetCore.Hosting.ConventionBasedStartup.ConfigureServices(IServiceCollection services)
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.EnsureApplicationServices()
   at Microsoft.AspNetCore.Hosting.Internal.WebHost.Initialize()
   at Microsoft.AspNetCore.Hosting.WebHostBuilder.Build()
   at Microsoft.AspNetCore.TestHost.TestServer..ctor(IWebHostBuilder builder, IFeatureCollection featureCollection)
   at Web.IntegrationTests.Common.TestFixture`1..ctor(String relativeTargetProjectPatentDir) in C:\...\test\Web.IntegrationTests\Common\TestFixture.cs:line 111
   at Web.IntegrationTests.Common.TestFixture`1..ctor() in C:\...\test\Web.IntegrationTests\Common\TestFixture.cs:line 68
   at Web.IntegrationTests.MvcTests.StockProfileTests.StockProfilesControllerTests..ctor() in C:\...\test\Web.IntegrationTests\MvcTests\StockTests\StockControllerTests.cs:line 25

如果我重新运行测试套件,则先前通过的其他测试将失败,而先前失败的测试现在将通过。另外,如果我重新运行失败的单个测试,它们也将通过。

我注意到的一件事是,每个堆栈跟踪都包括对AddAutoMapperClasses的调用。我已经对这个错误和AutoMapper进行了一些搜索,但没有发现任何东西。

我的问题很简单,有没有人看到此错误或有关可能导致此错误的任何想法?

1 个答案:

答案 0 :(得分:0)

它似乎正在下降,原因是并行并行地对Automapper进行了多次初始化。 我用xUnit的强力解决了这个问题:

using Xunit;

[assembly: CollectionBehavior(DisableTestParallelization = true)]

只需将其放置在项目源中的任何位置即可防止并行测试运行。