在不使用Microsoft.AspNetCore.TestHost中包含的TestServer的情况下运行Kestrel进行测试

Kas*_*r P 2 c# testing kestrel-http-server asp.net-core asp.net-core-2.0

我正在使用SoapCore使用asp.net core 2创建WCF类的应用程序。

这样做对我来说很好,但是在集成测试端点时遇到了一些障碍。

由于SoapCore是中间件,并且与任何api控制器都没有关系,因此我无法使用HttpClient来测试端点,因此TestServer对我没有用。

我的问题是在不使用TestServer的情况下如何与我的集成测试并行运行kestrel,或者在这种情况下是否可以利用TestServer?

我认为这里的任何代码都没有用,但是到目前为止,我得到的是以下内容。

启动文件

public class Startup
{
    public Startup(IConfiguration configuration)
    {
        Configuration = configuration;
    }

    public IConfiguration Configuration { get; }

    public void ConfigureServices(IServiceCollection services)
    {
        services.AddTransient<IPaymentService>(service => new Services.PaymentService());
        services.AddMvc();
    }

    public void Configure(IApplicationBuilder app, IHostingEnvironment env)
    {
        if (env.IsDevelopment())
        {
            app.UseDeveloperExceptionPage();
        }

        app.UseSoapEndpoint<IPaymentService>("/PaymentService.svc", new BasicHttpBinding());
        app.UseMvc();
    }
}
Run Code Online (Sandbox Code Playgroud)

PaymentService

[ServiceContract]
public interface IPaymentService
{
    [OperationContract]
    string ReadPaymentFiles(string caller);
}

 public class PaymentService : IPaymentService
{
    public string ReadPaymentFiles(string caller)
    {
        return caller;
    }
}
Run Code Online (Sandbox Code Playgroud)

我的测试之一:

public void Should_Get_Soap_Response_From_PaymentService()
    {
        var testServerFixture = new TestServerFixture();
        var binding = new BasicHttpBinding();
        var endpoint = new EndpointAddress(new Uri("http://localhost:5000/PaymentService.svc"));
        var channelFactory = new ChannelFactory<IPaymentService>(binding, endpoint);

        var serviceClient = channelFactory.CreateChannel();
        var response = serviceClient.ReadPaymentFiles("Ping");
        channelFactory.Close();
    }
Run Code Online (Sandbox Code Playgroud)

该测试现在不执行任何操作,因为它没有调用任何活动的端点,这是我的问题...

Ade*_*mak 5

您可以使用类似Microsoft.AspNetCore.Hosting包的自托管。在执行测试之前,您可以运行webHost,然后在该主机上执行文本。

public MyTestStartup()
{
    _webhost = WebHost.CreateDefaultBuilder(null)
                      .UseStartup<Startup>()
                      .UseKestrel()
                      .UseUrls(BASE_URL)
                      .Build();
    _webhost.Start();
}
Run Code Online (Sandbox Code Playgroud)

  • 我在我的存储库中使用此解决方案(https://github.com/AdemCatamak/ReadyApi.Core/blob/master/Tests/ReadyApi.Core.Test/Controllers/DefaultControllerTest.cs)。我希望这可以帮助你。 (2认同)