如何在单元测试中初始化CoreWCF.OperationContext?
解决CoreWCF .NET 6单元测试中初始化OperationContext的问题
核心方案:用CoreWCF的OperationContextScope+模拟/构造IContextChannel
方式1:轻量模拟(推荐单元测试用)
借助Moq模拟IContextChannel,配合InstanceContext和OperationContextScope初始化OperationContext.Current,无需创建真实通道:
// 需提前引用Moq和CoreWCF.Primitives包 using CoreWCF; using Moq; [Test] public void TestServiceSetsCustomStatusCode() { // 模拟IContextChannel var mockChannel = new Mock<IContextChannel>(); // 创建服务实例的InstanceContext var instanceContext = new InstanceContext(new YourManagementService()); // 构建CoreWCF的OperationContext var operationContext = new OperationContext(mockChannel.Object); // 用OperationContextScope将当前上下文设置为构建的实例 using (new OperationContextScope(operationContext)) { // 执行待测试的服务方法 var service = new YourManagementService(); service.YourMethodThatSetsCustomStatusCode(); // 验证自定义状态码是否正确设置 var responseProp = OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; Assert.Equal(HttpStatusCode.BadRequest, responseProp?.StatusCode); } }
方式2:使用CoreWCF原生ChannelFactory
如果需要贴近真实运行环境的测试,可使用CoreWCF自带的ChannelFactory(注意是CoreWCF命名空间下的类型,而非System.ServiceModel):
using CoreWCF; [Test] public void TestWithRealChannel() { // 使用CoreWCF的绑定和终结点地址 var binding = new BasicHttpBinding(); var endpoint = new EndpointAddress("http://localhost/Program.Interface/ManagementService.svc"); // 创建CoreWCF的ChannelFactory var factory = new ChannelFactory<IManagementService>(binding, endpoint); var channel = factory.CreateChannel(); // 初始化OperationContext.Current OperationContext.Current = new OperationContext(channel as IContextChannel); try { // 执行测试逻辑 var service = new YourManagementService(); service.YourMethodThatSetsCustomStatusCode(); // 验证结果 var responseProp = OperationContext.Current.OutgoingMessageProperties[HttpResponseMessageProperty.Name] as HttpResponseMessageProperty; Assert.NotNull(responseProp); Assert.Equal(HttpStatusCode.NotFound, responseProp.StatusCode); } finally { (channel as IClientChannel)?.Close(); factory.Close(); } }
为什么旧方法/HttpContextAccessor无效?
- 旧WCF Framework的
ChannelFactory属于System.ServiceModel命名空间,和CoreWCF的服务契约不兼容,必须使用CoreWCF命名空间下的对应类型。 HttpContextAccessor操作的是ASP.NET Core的HttpContext,而CoreWCF的响应状态码由自身OperationContext管理,二者是独立上下文,修改HttpContext不会影响CoreWCF返回的状态码。
内容的提问来源于stack exchange,提问作者dotnetammar
相关产品推荐
相关产品推荐

