2

フレームワーク&パッケージ統合テストは、コンフィギュレーションに

.NETCoreApp 1.1 
Xunit 2.2.0 
AutoMapper 6.0.2 
Microsoft.AspNetCore.TestHost 1.1.1 
Microsoft.NET.Test.Sdk 15.0.0 

統合テスト

public class ControllerRequestsShould 
{ 
    private readonly TestServer _server; 
    private readonly HttpClient _client; 

    public ControllerRequestsShould() 
    { 
     _server = new TestServer(new WebHostBuilder() 
      .UseContentRoot(Constants.apiProjectRoot) 
      .UseStartup<Startup>() 
      .UseEnvironment(Constants.testingEnvironment)); 
     _client = _server.CreateClient(); 
     _client.BaseAddress = new Uri(Constants.localHostUri); 
    } 

    [Fact] 
    public async Task CreateAnEntity() 
    { 
     // Arrange 
     var entityForCreationDto = new entityForCreationDto { Code = "00001", Name = "Entity One" }; 
     var jsonContent = JsonConvert.SerializeObject(entityForCreationDto); 
     var stringContent = new StringContent(jsonContent); 
     stringContent.Headers.ContentType = new MediaTypeHeaderValue("application/json"); 

     // Act 
     var response = await _client.PostAsync("/api/controller", stringContent); 
     response.EnsureSuccessStatusCode(); 

     // Assert 
     Assert.Equal(HttpStatusCode.OK, response.StatusCode); 
    } 
} 

Startup.cs

public class Startup 
{ 
    public IConfigurationRoot Configuration { get; } 

    public Startup(IHostingEnvironment env) 
    { 
     var builder = new ConfigurationBuilder() 
      .SetBasePath(env.ContentRootPath) 
      .AddJsonFile("appsettings.json", optional: true, reloadOnChange: true) 
      .AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true) 
      .AddEnvironmentVariables(); 
     Configuration = builder.Build(); 
    } 

    // This method gets called by the runtime. Use this method to add services to the container. 
    // For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940 
    public void ConfigureServices(IServiceCollection services) 
    { 
     // Add framework services 
     services.AddMvc(setupAction => 
     { 
      setupAction.ReturnHttpNotAcceptable = true; 
      setupAction.OutputFormatters.Add(new XmlDataContractSerializerOutputFormatter()); 
      setupAction.InputFormatters.Add(new XmlDataContractSerializerInputFormatter()); 
     }); 

     // Db context configuration 
     var connectionString = Configuration["ConnectionStrings:DefaultConnection"]; 
     services.AddDbContext<YourContext>(options => 
     { 
      options.UseSqlServer(connectionString); 
     }); 

     // Register services for dependency injection 
     services.AddScoped<IYourRepository, YourRepository>(); 

     services.AddSingleton<IActionContextAccessor, ActionContextAccessor>(); 

     services.AddScoped<IUrlHelper, UrlHelper>(implementationFactory => 
     { 
      var actionContext = 
       implementationFactory.GetService<IActionContextAccessor>().ActionContext; 
      return new UrlHelper(actionContext); 
     }); 
    } 

    // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. 
    public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) 
    { 
     loggerFactory.AddConsole(); 
     loggerFactory.AddDebug(LogLevel.Information); 
     loggerFactory.AddNLog(); 

     if (env.IsDevelopment()) 
     { 
      app.UseDeveloperExceptionPage(); 
     } 
     else 
     { 
      app.UseExceptionHandler(appBuilder => 
      { 
       appBuilder.Run(async context => 
       { 
        var exceptionHandlerFeature = context.Features.Get<IExceptionHandlerFeature>(); 
        if (exceptionHandlerFeature != null) 
        { 
         var logger = loggerFactory.CreateLogger("Global exception logger"); 
         logger.LogError(500, 
          exceptionHandlerFeature.Error, 
          exceptionHandlerFeature.Error.Message); 
        } 

        context.Response.StatusCode = 500; 
        await context.Response.WriteAsync("An unexpected fault happened. Try again later"); 
       }); 
      }); 
     } 

     Mapper.Initialize(cfg => 
     { 
      cfg.CreateMap<DataStore.Entities.Entity, Models.EntityDto>(); 
      cfg.CreateMap<Models.EntityDto, DataStore.Entities.Entity>(); 
      cfg.CreateMap<Models.EntityForCreationDto, DataStore.Entities.Entity>(); 
      cfg.CreateMap<DataStore.Entities.Entity, Models.EntityForCreationDto>(); 
     }); 

     app.UseMvc(); 
    } 
を初期化に失敗しますコントローラメソッドが呼び出された後

問題は、統合テストは失敗します。

var response = await _client.PostAsync("/api/controller", stringContent); 

AutoMapperが初期化されていないので、それが失敗しました。 私はこれを理解方法はTestServerUseStartupメソッドを持っているので、これは明らかに起きていない

UseContentRootは私のAPIプロジェクトのルートを指している)API Startup.csクラスで構成されているすべてのサービスを使用する必要があるということでした。誰かが私にどのようにTestServerを設定する必要があるのか​​を教えてもらえますか?AutoMapperの設定が正しく拾われるようにしてください。マッピングの設定がAutoMapperによって自動的にピックアップされるので、私はAutomapperモジュールを使用してい var assembly = typeof(Program).GetTypeInfo().Assembly; services.AddAutoMapper(assembly); 、それでも、あなたはまだ上記の設定が必要になります。

+0

表示する起動クラス – Nkosi

+0

でより明確かつクリーンである

var assembly = typeof(Program).GetTypeInfo().Assembly; services.AddAutoMapper(assembly); 

services.AddAutoMapper(typeof(Startup)); 

を使うのか? – bigyanshr

答えて

1

あなたはConfigureServices方法でアセンブリを指定する必要があります。

1

それとも、このラインの代わりに、あなたがこの問題のいずれかの解決策を見つけるか私の意見