【问题标题】:Use NInject to provide Rhino Mock objects to WebApi controllers - Stubs allways return null使用 NInject 向 WebApi 控制器提供 Rhino Mock 对象 - 存根总是返回 null
【发布时间】:2017-03-10 17:34:05
【问题描述】:

我正在尝试使用从我的 [ClassInitialize](MS 测试)方法调用的 Owin 内存服务器对我的 WebApi 控制器进行单元测试。我需要通过 DI 容器将我的存储库对象 IFourSquareRepository 的模拟实例注入到我的控制器中。当测试类 [ClassInitialize] 方法执行时,Owin 服务器设置、静态 Ninject IKernel 实例及其绑定在 WebApi 项目中的 Owin 配置类中处理:

            kernel.Bind<IFourSquareRepository>().ToMethod( 
            context => 
                {
                    return MockRepository.GenerateMock<IFourSquareRepository>(); 
                    // This block runs only once ...
                    // But stubs from the test method return null when the test call 
                    // fires up the controller ...
                }
                ).InSingletonScope();

当在我的测试项目的测试方法中进行评估时,这些存根可预测地工作(即:它们返回我在下面的存根定义中指定的值)。

我的 [TestMethod] 案例为我的控制器所依赖的模拟接口 (IFourSquareRepository) 的方法创建存根,并调用解析到我的 WebApi 上的 WebApi 端点控制器如下所示 - (当我发送 HttpClient 请求时,我无法手动将我的模拟对象注入控制器实例 - 我依靠 WebApi 管道来创建控制器实例,所以我必须使用 DI 容器来注入一个模拟的 IFourSquareRepository 对象到控制器中):

       [TestMethod]
    public void Test1_InMemServer()
    {
        var testRet = new BookmarkedPlace() { Id = 99 };
        string userName = "Joe";
        this.MockRepository.Stub(
            repo => repo.GetFirstBookmarkedPlace()).Return(testRet);
        // stub for test Repo IF method

        // Act User the base class static HttpClient to talk to the Owin-hosted WebApi  
        var response = InMemoryTest.HttpClient.GetAsync( string.Format("/api/places/{0}", userName) ).Result;
        var body = response.Content.ReadAsStringAsync().Result;

        // Assert
        Assert.IsTrue(response.IsSuccessStatusCode, "Request Failed ");


    }

我的问题是,无论我做什么,当控制器(从我上面的 HttpClient 请求中调用)调用存根方法时,它总是返回 NULL !!

       public IEnumerable<BookmarkedPlace> Get(string userName, int page = 0, int pageSize = 10)
    {
        IQueryable<BookmarkedPlace> query;

        query = this.Repository.GetFirstBookmarkedPlace();
        // Mock Repo call returning null !

        // Other stuff goes here ...

        return results;

    }

这几天我一直在思考这个问题 - 有什么想法吗?

【问题讨论】:

    标签: asp.net-web-api ninject owin rhino-mocks


    【解决方案1】:

    我认为原因是当您创建模拟存储库时,我确信后端必须使用某种上下文作为调用的依赖项也会被存根,因此不会映射到实际的数据库集。

    过去我使用下面的方法来模拟我的存储库并在我的 Base Test 类中获取 DbSet 的实例(因为这对生成很常见)

    public static IDbSet<T> GenerateSet<T>(IList<T> data) where T : class
        {
            IQueryable<T> queryable = data.AsQueryable();
            IDbSet<T> dbSet = MockRepository.GenerateMock<IDbSet<T>, IQueryable>();
            dbSet.Stub(x => x.Provider).Return(queryable.Provider);
            dbSet.Stub(x => x.Expression).Return(queryable.Expression);
            dbSet.Stub(x => x.ElementType).Return(queryable.ElementType);
            dbSet.Stub(x => x.GetEnumerator()).Return(null).WhenCalled(x => queryable.GetEnumerator());
    
            return dbSet;
        }
    

    然后在我做的 Initialise 的 Test 类中:

    [TestInitialize]
        public new void Initialize()
        {
            base.Initialize();
            _context = MockRepository.GenerateMock<YourContextInterface>();
            _context.Stub(x => x.YourDbSet).PropertyBehavior();
            _context.YourDbSet= GenerateSet(YourDbSet);
        }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-08-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-09-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多