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以及如何正确设置它.

相关文章

### 创建一个gRPC服务项目(grpc服务端)和一个 webapi项目(...
一、SiganlR 使用的协议类型 1.websocket即时通讯协议 2.Ser...
.Net 6 WebApi 项目 在Linux系统上 打包成Docker镜像,发布为...
一、 PD简介PowerDesigner 是一个集所有现代建模技术于一身的...
一、存储过程 存储过程就像数据库中运行的方法(函数) 优点:...
一、Ueditor的下载 1、百度编辑器下载地址:http://ueditor....