And*_*ter 3 asp.net odata asp.net-web-api
我尝试单元测试EntitySetController.我可以测试Get但在测试Post方法时遇到问题.
我使用了SetODataPath和SetODataRouteName,但是当我调用this.sut.Post(实体)时,我遇到了很多关于丢失位置标头,丢失OData-Path,丢失路由的错误.
我没办法.有没有人成功测试他们的EntitySetController?
对我有什么想法吗?也许我应该只测试我的EntitySetController实现中受保护的覆盖方法?但是我如何测试受保护的方法呢?
谢谢你的帮助
小智 5
来这里寻找解决方案.这似乎工作,但不确定是否有更好的方法.
控制器需要最少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;
}
}
Run Code Online (Sandbox Code Playgroud)
MyEntity非常简单:
public class MyEntity
{
public int Id { get; set; }
public string Name { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
看起来您至少需要:+在请求标头中请求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);
}
Run Code Online (Sandbox Code Playgroud)
我不太确定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
}
Run Code Online (Sandbox Code Playgroud)
这是为我工作不过我真的不太确定的ODataPath
,并IHttpRoute
和如何正确设置它.
归档时间: |
|
查看次数: |
1184 次 |
最近记录: |