C# 如何使用RestSharp模拟OWIN测试服务器?
我将OWIN与WebAPI集成作为WebApp使用。未来的计划是使用OWIN自托管,它工作正常,但OWIN testserver实现无法与RestSharp一起工作: 未经重新整理的样品: 第一种尝试是使用从RestClient类派生的模拟类: 公共类MockRestClient:RestClient { 公共测试服务器测试服务器{get;set;}C# 如何使用RestSharp模拟OWIN测试服务器?,c#,unit-testing,mocking,owin,restsharp,C#,Unit Testing,Mocking,Owin,Restsharp,我将OWIN与WebAPI集成作为WebApp使用。未来的计划是使用OWIN自托管,它工作正常,但OWIN testserver实现无法与RestSharp一起工作: 未经重新整理的样品: 第一种尝试是使用从RestClient类派生的模拟类: 公共类MockRestClient:RestClient { 公共测试服务器测试服务器{get;set;} public MockRestClient(TestServer testServer) { TestServe
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
var response = TestServer.HttpClient.GetAsync(request.Resource).Result;
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}
不幸的是,我坚持使用Post事件,这需要restResponse提供html正文
有人做过类似的事情吗
顺便说一句:我也可以将OWIN单元测试与自托管OWIN一起使用,但这在Teamcity自动构建上不起作用。我将模拟rest客户端也更改为使用Post/Put/Delete方法。它不是100%完成的(缺少身份验证、cookie、文件等),但在我的情况下就足够了:
public class MockRestClient : RestClient
{
public TestServer TestServer { get; set; }
public MockRestClient(TestServer testServer)
{
TestServer = testServer;
}
public override IRestResponse Execute(IRestRequest request)
{
// TODO: Currently the test server is only doing GET requests via RestSharp
HttpResponseMessage response = null;
Parameter body = request.Parameters.FirstOrDefault(p => p.Type == ParameterType.RequestBody);
HttpContent content;
if (body != null)
{
object val = body.Value;
byte[] requestBodyBytes;
string requestBody;
if (val is byte[])
{
requestBodyBytes = (byte[]) val;
content = new ByteArrayContent(requestBodyBytes);
}
else
{
requestBody = Convert.ToString(body.Value);
content = new StringContent(requestBody);
}
}
else
content = new StringContent("");
string urladd = "";
IEnumerable<string> @params = from p in request.Parameters
where p.Type == ParameterType.GetOrPost && p.Value != null
select p.Name + "=" + p.Value;
if(!@params.IsNullOrEmpty())
urladd = "?" + String.Join("&", @params);
IEnumerable<HttpHeader> headers = from p in request.Parameters
where p.Type == ParameterType.HttpHeader
select new HttpHeader
{
Name = p.Name,
Value = Convert.ToString(p.Value)
};
foreach (HttpHeader header in headers)
{
content.Headers.Add(header.Name, header.Value);
}
content.Headers.ContentType.MediaType = "application/json";
switch (request.Method)
{
case Method.GET:
response = TestServer.HttpClient.GetAsync(request.Resource + urladd).Result;
break;
case Method.DELETE:
response = TestServer.HttpClient.DeleteAsync(request.Resource + urladd).Result;
break;
case Method.POST:
response = TestServer.HttpClient.PostAsync(request.Resource + urladd, content).Result;
break;
case Method.PUT:
response = TestServer.HttpClient.PutAsync(request.Resource + urladd, content).Result;
break;
default:
return null;
}
var restResponse = ConvertToRestResponse(request, response);
return restResponse;
}
private static RestResponse ConvertToRestResponse(IRestRequest request, HttpResponseMessage httpResponse)
{
RestResponse restResponse1 = new RestResponse();
restResponse1.Content = httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding = httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength = (long)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType = httpResponse.Content.Headers.ContentType.ToString();
if (httpResponse.IsSuccessStatusCode == false)
{
restResponse1.ErrorException = new HttpRequestException();
restResponse1.ErrorMessage = httpResponse.Content.ToString();
restResponse1.ResponseStatus = ResponseStatus.Error;
}
restResponse1.RawBytes = httpResponse.Content.ReadAsByteArrayAsync().Result;
restResponse1.ResponseUri = httpResponse.Headers.Location;
restResponse1.Server = "http://localhost";
restResponse1.StatusCode = httpResponse.StatusCode;
restResponse1.StatusDescription = httpResponse.ReasonPhrase;
restResponse1.Request = request;
RestResponse restResponse2 = restResponse1;
foreach (var httpHeader in httpResponse.Headers)
restResponse2.Headers.Add(new Parameter()
{
Name = httpHeader.Key,
Value = (object)httpHeader.Value,
Type = ParameterType.HttpHeader
});
//foreach (var httpCookie in httpResponse.Content.)
// restResponse2.Cookies.Add(new RestResponseCookie()
// {
// Comment = httpCookie.Comment,
// CommentUri = httpCookie.CommentUri,
// Discard = httpCookie.Discard,
// Domain = httpCookie.Domain,
// Expired = httpCookie.Expired,
// Expires = httpCookie.Expires,
// HttpOnly = httpCookie.HttpOnly,
// Name = httpCookie.Name,
// Path = httpCookie.Path,
// Port = httpCookie.Port,
// Secure = httpCookie.Secure,
// TimeStamp = httpCookie.TimeStamp,
// Value = httpCookie.Value,
// Version = httpCookie.Version
// });
return restResponse2;
}
公共类MockRestClient:RestClient
{
公共测试服务器测试服务器{get;set;}
公共MockRestClient(TestServer TestServer)
{
TestServer=TestServer;
}
公共覆盖IRestResponse执行(IRestRequest请求)
{
//TODO:当前测试服务器仅通过RestSharp执行GET请求
HttpResponseMessage响应=null;
参数body=request.Parameters.FirstOrDefault(p=>p.Type==ParameterType.RequestBody);
http含量;
if(body!=null)
{
object val=body.Value;
字节[]请求体字节;
字符串请求体;
if(val是字节[])
{
requestBodyBytes=(字节[])val;
内容=新的ByteArrayContent(requestBodyBytes);
}
其他的
{
requestBody=Convert.ToString(body.Value);
内容=新的StringContent(请求主体);
}
}
其他的
内容=新的字符串内容(“”);
字符串urladd=“”;
IEnumerable@params=来自请求中的p.Parameters
其中p.Type==ParameterType.GetOrPost&&p.Value!=null
选择p.名称+“=”+p.值;
if(!@params.IsNullOrEmpty())
urladd=“?”+String.Join(“&”,@params);
IEnumerable headers=来自request.Parameters中的p
其中p.Type==参数Type.HttpHeader
选择新建HttpHeader
{
名称=p.名称,
Value=Convert.ToString(p.Value)
};
foreach(头中的HttpHeader)
{
content.Headers.Add(header.Name,header.Value);
}
content.Headers.ContentType.MediaType=“应用程序/json”;
开关(请求方法)
{
case-Method.GET:
response=TestServer.HttpClient.GetAsync(request.Resource+urladd).Result;
打破
案例方法.删除:
response=TestServer.HttpClient.DeleteAsync(request.Resource+urladd).Result;
打破
case-Method.POST:
response=TestServer.HttpClient.PostAsync(request.Resource+urladd,content).Result;
打破
case-Method.PUT:
response=TestServer.HttpClient.PutAsync(request.Resource+urladd,content).Result;
打破
违约:
返回null;
}
var response=转换器响应(请求、响应);
返回重响应;
}
专用静态Response转换器响应(IRestRequest请求、httpResponse消息httpResponse)
{
RestResponse restResponse1=新的RestResponse();
resresponse1.Content=httpResponse.Content.ReadAsStringAsync().Result;
restResponse1.ContentEncoding=httpResponse.Content.Headers.ContentEncoding.FirstOrDefault();
restResponse1.ContentLength=(长)httpResponse.Content.Headers.ContentLength;
restResponse1.ContentType=httpResponse.Content.Headers.ContentType.ToString();
如果(httpResponse.IsSuccessStatusCode==false)
{
restResponse1.ErrorException=新的HttpRequestException();
restResponse1.ErrorMessage=httpResponse.Content.ToString();
restResponse1.ResponseStatus=ResponseStatus.Error;
}
resresponse1.RawBytes=httpResponse.Content.ReadAsByteArrayAsync().Result;
resresponse1.ResponseUri=httpResponse.Headers.Location;
resresponse1.Server=”http://localhost";
restResponse1.StatusCode=httpResponse.StatusCode;
restResponse1.StatusDescription=httpResponse.ReasonPhase;
resresponse1.Request=请求;
RestResponse restResponse2=restResponse1;
foreach(httpResponse.Headers中的var httpHeader)
resresponse2.Headers.Add(新参数()
{
Name=httpHeader.Key,
Value=(对象)httpHeader.Value,
Type=参数Type.HttpHeader
});
//foreach(httpResponse.Content中的var httpCookie。)
//添加(新的RestResponseCookie())
// {
//Comment=httpCookie.Comment,
//CommentUri=httpCookie.CommentUri,
//Discard=httpCookie.Discard,
//Domain=httpCookie.Domain,
//Expired=httpCookie.Expired,
//Expires=httpCookie.Expires,
//HttpOnly=httpCookie.HttpOnly,
//Name=httpCookie.Name,
//Path=httpCookie.Path,
//Port=httpCookie.Port,
//Secure=httpCookie.Secure,
//TimeStamp=httpCookie.TimeStamp,
//Value=httpCookie.Value,
//版本=httpCooki