基于@Craig (OP) 的回答代码的更新,但适用于您没有生成的 WCF 客户端的情况。IMySoapSvc
此答案进一步提供了完整设置的代码。
using System;
using System.ServiceModel;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using MyMicroservice;
using MyMicroservice.SoapSvc;
using Xunit;
namespace XUnitTestProject.Craig
{
public class WcfWebApplicationFactoryTest : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public WcfTest(WebApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Fact]
public async Task sayHello_normalCond_receive_HelloWorld()
{
await Task.Delay(1); // because of some issues with WebApplicationFactory, test method needs to be async
var endpoint = new EndpointAddress(new Uri("http://localhost/MyService.svc"));
var binding = new BasicHttpBinding(BasicHttpSecurityMode.None);
using var channelFactory = new ChannelFactory<IMySoapSvc>(binding, endpoint);
// entry point for code from @Craig
channelFactory.Endpoint.InterceptRequestsWithHttpClient(_factory.CreateClient());
var wcfClient = channelFactory.CreateChannel();
var response = wcfClient.SayHello();
Assert.Equal("Hello world", response);
}
}
}
使用 SOAP 客户端的替代方法是使用常规 POST 请求。
下面是支持 SOAP 1.1 和 1.2 的简单 Hello World SOAP 服务的分步说明。最后,有几个测试使用WebApplicationFactory
,然后使用ChannelFactory
。
添加此 Nuget(或可用时更新)
<PackageReference Include="SoapCore" Version="1.1.0.7" />
SOAP 服务
using System.ServiceModel;
namespace MyMicroservice.SoapSvc
{
[ServiceContract(Name = "MySoapSvc", Namespace = "http://www.mycompany.no/mysoap/")]
public interface IMySoapSvc
{
[OperationContract(Name = "sayHello")]
string SayHello();
}
public class MySoapSvc : IMySoapSvc
{
public string SayHello()
{
return "Hello world";
}
}
}
启动#ConfigureServices
using var iisUrlRewriteStreamReader = File.OpenText("RewriteRules.xml");
var options = new RewriteOptions()
.AddIISUrlRewrite(iisUrlRewriteStreamReader);
app.UseRewriter(options);
services.AddSingleton<IMySoapSvc, MySoapSvc>();
启动#配置
var soap12Binding = new CustomBinding(new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, System.Text.Encoding.UTF8),
new HttpTransportBindingElement());
app.UseSoapEndpoint<IMySoapSvc>("/MyService.svc", new BasicHttpBinding(), SoapSerializer.XmlSerializer);
app.UseSoapEndpoint<IMySoapSvc>("/MyService12.svc", soap12Binding, SoapSerializer.XmlSerializer);
重写规则以在 SOAP 1.1/1.2 之间进行拆分。将其放在与Startup.cs相同的文件夹中的文件RewriteRules.xml中。
<rewrite>
<rules>
<rule name="Soap12" stopProcessing="true">
<match url="(.*)\.svc" />
<conditions>
<add input="{REQUEST_METHOD}" pattern="^POST$" />
<add input="{CONTENT_TYPE}" pattern=".*application/soap\+xml.*" />
</conditions>
<action type="Rewrite" url="/{R:1}12.svc" appendQueryString="false" />
</rule>
</rules>
</rewrite>
您需要在RewriteRules.xml的项目文件中使用它
<ItemGroup>
<None Update="RewriteRules.xml">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
</ItemGroup>
最后是测试。在这里,我们可以看到 SOAP 1.1 和 SOAP 1.2 请求之间的详细差异。
using System.Net;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc.Testing;
using MyMicroservice;
using Xunit;
namespace XUnitTestProject
{
public class BasicTests : IClassFixture<WebApplicationFactory<Startup>>
{
private readonly WebApplicationFactory<Startup> _factory;
public BasicTests(WebApplicationFactory<Startup> factory)
{
_factory = factory;
}
[Theory]
[InlineData("/MyService.svc")]
public async Task helloWorld_validEnvelope11_receiveOk(string url) {
const string envelope = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
<soap:Body>
<sayHello xmlns=""http://www.mycompany.no/mysoap/""></sayHello>
</soap:Body>
</soap:Envelope>";
var client = _factory.CreateClient();
client.DefaultRequestHeaders.Add("SOAPAction", "http://localhost/mysoap/sayHello");
var response = await client
.PostAsync(url, new StringContent(envelope, Encoding.UTF8, "text/xml"));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Hello world", await response.Content.ReadAsStringAsync());
}
[Theory]
[InlineData("/MyService.svc")]
public async Task helloWorld_validEnvelope12_receiveOk(string url)
{
const string envelope = @"<?xml version=""1.0"" encoding=""utf-8""?>
<soap12:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance""
xmlns:xsd=""http://www.w3.org/2001/XMLSchema""
xmlns:soap12=""http://www.w3.org/2003/05/soap-envelope"">
<soap12:Body >
<sayHello xmlns=""http://www.mycompany.no/mysoap/""></sayHello>
</soap12:Body>
</soap12:Envelope>";
var client = _factory.CreateClient();
var response = await client
.PostAsync(url, new StringContent(envelope, Encoding.UTF8, "application/soap+xml"));
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
Assert.Contains("Hello world", await response.Content.ReadAsStringAsync());
}
}
}
另一种方法是使用ChannelFactory
在端口 5000 上运行普通主机的客户端。为此,我们需要在测试基类中启动 Web 环境。这种方法的运行速度明显快于WebApplicationFactory
. 请参阅此答案末尾的屏幕截图。
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using MyMicroservice;
using Xunit;
namespace XUnitTestProject
{
public class HostFixture : IAsyncLifetime
{
private IHost _host;
public async Task InitializeAsync()
{
_host = CreateHostBuilder().Build();
await _host.StartAsync();
}
public async Task DisposeAsync()
{
await _host.StopAsync();
_host.Dispose();
}
private static IHostBuilder CreateHostBuilder() =>
Host.CreateDefaultBuilder(Array.Empty<string>())
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
}
}
然后是测试课。这是非常标准的代码。
using System;
using System.ServiceModel;
using System.ServiceModel.Channels;
using MyMicroservice.SoapSvc;
using Xunit;
namespace XUnitTestProject
{
public class WcfTest : IClassFixture<HostFixture>
{
[Theory]
[InlineData("http://localhost:5000/MyService.svc")]
public void sayHello_normalCond_receiveHelloWorld11(string url)
{
var binding = new BasicHttpBinding();
var endpoint = new EndpointAddress(new Uri(url));
using var channelFactory = new ChannelFactory<IMySoapSvc>(binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var response = serviceClient.SayHello();
Assert.Equal("Hello world", response);
}
[Theory]
[InlineData("http://localhost:5000/MyService.svc")]
public void sayHello_normalCond_receiveHelloWorld12(string url)
{
var soap12Binding = new CustomBinding(
new TextMessageEncodingBindingElement(MessageVersion.Soap12WSAddressingAugust2004, System.Text.Encoding.UTF8),
new HttpTransportBindingElement());
var endpoint = new EndpointAddress(new Uri(url));
using var channelFactory = new ChannelFactory<IMySoapSvc>(soap12Binding, endpoint);
var serviceClient = channelFactory.CreateChannel();
var response = serviceClient.SayHello();
Assert.Equal("Hello world", response);
}
}
}
显示测试已用时间的屏幕截图。获胜者WcfTest
使用在端口 5000 上运行的主机,第二名是BasicTests
使用WebApplicationFactory
普通 POST 请求。

更新:由于设置时间更短,使用 NUnit 和WebApplicationFactory
(此处未显示)进行测试的速度提高了 4 倍。
使用 .NET Core 5 进行测试。