我也在寻找解决方案。这种方法似乎有效,但不确定是否有更好的方法。
控制器需要至少覆盖CreateEntity
和GetKey
:
public class MyController : EntitySetController<MyEntity, int>
{
protected override MyEntity CreateEntity(MyEntity entity)
{
return entity;
}
protected override int GetKey(MyEntity entity)
{
return entity.Id;
}
}
MyEntity非常简单:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
看起来您至少需要:
+ 带有URI的请求
+ 请求头中的3个关键字,MS_HttpConfiguration
, MS_ODataPath
和MS_ODataRouteName
+ 一个带有路由的HTTP配置
[TestMethod]
public void CanPostToODataController()
{
var controller = new MyController();
var config = new HttpConfiguration();
var request = new HttpRequestMessage();
config.Routes.Add("mynameisbob", new MockRoute());
request.RequestUri = new Uri("http://www.thisisannoying.com/MyEntity");
request.Properties.Add("MS_HttpConfiguration", config);
request.Properties.Add("MS_ODataPath", new ODataPath(new EntitySetPathSegment("MyEntity")));
request.Properties.Add("MS_ODataRouteName", "mynameisbob");
controller.Request = request;
var response = controller.Post(new MyEntity());
Assert.IsNotNull(response);
Assert.IsTrue(response.IsSuccessStatusCode);
Assert.AreEqual(HttpStatusCode.Created, response.StatusCode);
}
我对IHttpRoute
不太确定,在aspnet源代码中(为了弄清楚这一切,我不得不链接到此处),测试使用该接口的模拟。因此,对于这个测试,我只需创建一个该接口的模拟,并实现RouteTemplate
属性和GetVirtualPath
方法。在测试期间,没有使用接口上的其他方法。
public class MockRoute : IHttpRoute
{
public string RouteTemplate
{
get { return ""; }
}
public IHttpVirtualPathData GetVirtualPath(HttpRequestMessage request, IDictionary<string, object> values)
{
return new HttpVirtualPathData(this, "www.thisisannoying.com");
}
// implement the other methods but they are not needed for the test above
}
这对我来说是有效的,但我真的不太确定关于 ODataPath
和 IHttpRoute
如何正确设置它。