[英]IHTTPActionResult custom response and unit testing with WebApi 2
I have created a class which is as follows 我创建了一个如下的类
public class Response<T> : IHttpActionResult where T : class
{
private readonly T _body;
....
public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken)
{
HttpResponseMessage msg = new HttpResponseMessage();
switch (_httpStatus)
{
case HttpResponseStatus.Ok:
{
msg = _request.CreateResponse(HttpStatusCode.OK, _body);
break;
}
case HttpResponseStatus.BadRequest:
{
msg = _request.CreateResponse(HttpStatusCode.BadRequest, _body);
break;
}
...
return Task.FromResult(msg);
}
}
This is my base class for returning IHTTPActionResult in my web api calls. 这是我的Web API调用中返回IHTTPActionResult的基类。 It works well for what i require it for.
它可以很好地满足我的需求。
I now have some unit tests setup using MSTest. 我现在有一些使用MSTest进行的单元测试设置。
// Act
IHttpActionResult result = controller.Step1();
// Assert
Assert.IsNotNull(result, "Is null when it shouldnt be");
Assert.IsInstanceOfType(result, typeof(Response<BodyContent<LogingActivityResult>>), "Is not expected IsInstanceOfType");
Both of these Assertions work fine. 这两个断言都可以正常工作。 However i now want to actually get @ the data held within my response and assert that they are ok ie: correct values, counts, etc but am having no luck with this.
但是,我现在实际上想获取@包含在我的响应中的数据,并断言它们是可以的,即:正确的值,计数等,但是对此不走运。 I have tried ALL the various System.Web.Http.Results types such as
我已经尝试了所有各种System.Web.Http.Results类型,例如
var contentResult = result as OkNegotiatedContentResult<Response<BodyContent<LogingActivityResult>>>;
or 要么
var contentResult = result as FormattedContentResult<Response<BodyContent<LogingActivityResult>>>;
but both of these are null when i hover over contentResult variable. 但是当我将鼠标悬停在contentResult变量上时,这两个都是null。
Can anyone lead me in the right direction? 谁能引导我正确的方向?
Thanks 谢谢
I managed to solve this.. the property _body in my above class was set to PRIVATE, as a result I could not access this in my unit test class. 我设法解决了这个问题。.在上面的类中,属性_body设置为PRIVATE,结果我无法在单元测试类中访问此属性。 Setting it to PUBLIC solved it and was able to access the data being returned in the response.
将其设置为PUBLIC可以解决该问题,并且能够访问响应中返回的数据。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.