Rom*_*syk 8 c# asp.net-mvc asp.net-web-api
我BaseApiController班上有以下方法:
public virtual HttpResponseMessage GetById(int id)
{
var entity = repository.GetById(id);
if (entity == null)
{
var message = string.Format("No {0} with ID = {1}", GenericTypeName, id);
return ErrorMsg(HttpStatusCode.NotFound, message);
}
return Request.CreateResponse(HttpStatusCode.OK, SingleResult.Create(repository.Table.Where(t => t.ID == id)));
}
Run Code Online (Sandbox Code Playgroud)
我正在使用SingleResultOData请求(因为$expand如果我不创建SingleResult,单个实体不起作用).
但是现在我在具体控制器(例如AddressApiController)上遇到了这个方法的UnitTests问题.我总是得到NULL结果:
[TestMethod]
public void Get_By_Id()
{
//Arrange
var moq = CreateMockRepository();
var controller = new AddressApiController(moq);
controller.Request = new HttpRequestMessage()
controller.Request.SetConfiguration(new HttpConfiguration())
// Action
HttpResponseMessage response = controller.GetById(1);
var result = response.Content.ReadAsAsync<T>().Result;
// Accert
Assert.IsNotNull(result);
}
Run Code Online (Sandbox Code Playgroud)
我检查并调试GetById()并发现repository.Table.Where(t => t.ID == id))返回正确的值,但在SingleResult.Create我得到之后NULL.
我怎么解决这个问题?如何从SingleResult中读取内容或使用其他内容?
我创建了扩展:
public static class HttpResponseMessageExtensions
{
public static IQueryable<T> ContentToQueryable<T>(this HttpResponseMessage response) where T : BaseEntity
{
var objContent = response.Content as ObjectContent;
return objContent?.Value as IQueryable<T>;
}
public static T ContentToEntity<T>(this HttpResponseMessage response) where T : BaseEntity
{
var objContent = response.Content as ObjectContent;
return objContent?.Value as T;
}
}
Run Code Online (Sandbox Code Playgroud)
进而:
var result = response.ContentToEntity<T>();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
848 次 |
| 最近记录: |