微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

asp.net – 我如何单元测试EntitySetController

我尝试单元测试EntitySetController.我可以测试Get但在测试Post方法时遇到问题.

我使用了SetoDataPath和SetoDaTarouteName,但是当我调用this.sut.Post(实体)时,我遇到了很多关于丢失位置标头,丢失OData-Path,丢失路由的错误.

我没办法.
有没有人成功测试他们的EntitySetController?

有人对我有意见吗?
也许我应该只测试我的EntitySetController实现中受保护的覆盖方法?但是我如何测试受保护的方法呢?

谢谢你的帮助

解决方法

来这里寻找解决方案.这似乎工作,但不确定是否有更好的方法.

控制器需要最少的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以及如何正确设置它.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐