我目前正在为 WCF 应用程序编写单元测试。在 ServiceContract 的实现中,如果凭据错误,它会返回 401 响应。请参阅下面的代码:
public GenericResponse<string> GetAuthenticationToken()
{
try
{
var authToken = Task.Run(async () =>
{
var token = await _authenticationService.AuthenticationUser();
return token;
});
return new GenericResponse<string>()
{
ErrorMessage = string.Empty,
HasError = false,
ResponseObject = authToken.Result
};
}
catch (Exception ex) when (ex.InnerException.Message.StartsWith("Invalid credentials passed"))
{
// Set the HTTP status code
WebOperationContext.Current.OutgoingResponse.StatusCode = System.Net.HttpStatusCode.Unauthorized;
return new GenericResponse<string>
{
HasError = true,
ErrorMessage = "Invalid Credentials",
ResponseObject = ex.InnerException.Message
};
}
catch (Exception ex)
{
var fault = new GenericErrorResponse
{
ErrorMessage = $"An unknown error occured while authenticating",
ErrorCode = 500,
Details = $"An error occured while getting authentication token: {ex.Message}. {ex.InnerException?.Message ?? string.Empty}"
};
// Throw FaultException with custom fault
throw new FaultException<GenericErrorResponse>(fault, new FaultReason(fault.ErrorMessage));
}
}
如果传递了无效的凭据,我会返回 401,并且在运行服务时效果很好。然而,在为此类/方法编写单元测试时会出现问题。
[TestMethod]
public void GetAuthenticationToken()
{
mockAuthService.Setup(i => i.AuthenticationUser())
.Returns(() => Task.Run(() => VALID_TOKEN));
var expectedResponse = new GenericResponse<string>()
{
ErrorMessage = string.Empty,
HasError = false,
ResponseObject = VALID_TOKEN
};
var awsWcfFileStorageService = new AwsWcfFileStorageService(mockAuthService.Object,
mockS3FileService.Object);
var actualResponse = awsWcfFileStorageService.GetAuthenticationToken();
actualResponse.Should().BeEquivalentTo(expectedResponse);
}
当我运行单元测试时,出现以下异常错误
System.TypeLoadException: 'Could not load type 'System.ServiceModel.Web.WebOperationContext' from assembly 'System.ServiceModel.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35'.'
该异常的stackTrace如下:
at email_wcf_service.AwsWcfFileStorageService.GetAuthenticationToken() in D:\Projects\file-storage-windows-service\file-storage-wcf-service\FileStorageService.cs:line 89
at file_storage_wcf_service.Tests.FileStorageServiceTests.GetAuthenticationToken() in D:\Projects\file-storage-windows-service\file-storage-wcf-service.Tests\AwsWcfFileStorageServiceTests.cs:line 139
at System.RuntimeMethodHandle.InvokeMethod(Object target, Void** arguments, Signature sig, Boolean isConstructor)
at System.Reflection.MethodBaseInvoker.InvokeWithNoArgs(Object obj, BindingFlags invokeAttr)
我尝试匹配版本,但仍然没有帮助
问题可能是由
造成的var
actualResponse = awsWcfFileStorageService.GetAuthenticationToken()
;
它没有正确且成功地调用“System.ServiceModel.Web.WebOperationContext”。
首先建议您检查测试环境的程序项目环境与服务是否一致。您肯定需要测试人员来访问此测试服务代码。但你在问题中提到你已经尝试检查版本。所以我认为这也可能是框架本身的问题。目前在科尔有很多Sistems和Severemmore包可以安装,在麦克登据说效果很好。但实际上是无法引用的,会给出上面的错误信息。
其次,我认为原因可能是你在测试时没有使用HTTP请求。但是,System.ServiceModel.Web.WebOperationContext 需要 HTTP 请求,这可能会导致其无法初始化并且可能无法正确加载。