Stub工作单元和存储库

时间:2012-07-31 20:21:15

标签: c# .net asp.net-mvc rhino-mocks unit-of-work

我实现了一个UnitOfWork和Repository模式,如here所述,其中UnitOfWork包含对每个存储库的引用。我正在为我的项目添加单元测试,我想创建一个存根UnitOfWork。问题是我似乎无法让Rhino Mocks创建一个存根UnitOfWork,它会抛出异常。我认为原因是因为它试图获取数据库的连接字符串。有谁知道我做错了什么?

单元测试

[Test]
public void About_page_should_render()
{
    var unit = MockRepository.GenerateStub<UnitOfWork>(); //Throws exception
    var controller = new HomeController(unit);

    var result = controller.About() as ViewResult;

    Assert.NotNull(result);
}

工作单位结构

public class UnitOfWork
{
    private SampleRepository _sampleRepository;

    public SampleRepository SampleRepository 
    {
        get
        {
            if (this._sampleRepository == null)
                this._sampleRepository = new SampleRepository(context);

            return this._sampleRepository;
        }
    }
}

抛出空指针的方法

private static DbConnection GetConnection()
{
    return new SqlConnection(ConfigurationManager.ConnectionStrings[CON_STRING].ConnectionString);
}

堆栈跟踪

UnitTests.UI.Controllers.HomeControllerTester.About_page_should_render:
System.Exception : Exception in constructor: System.NullReferenceException: Object reference not set to an instance of an object.
   at DocumentManagement.Infrastrucuture.DataAccess.ViiadDbContext.GetConnection() in C:\Users\sbossbaly\Desktop\DocumentManagement\DocumentManagement\Infrastrucuture\DataAccess\ViiadDbContext.cs:line 42
   at DocumentManagement.Infrastrucuture.DataAccess.ViiadDbContext.GetProfiledConnection() in C:\Users\sbossbaly\Desktop\DocumentManagement\DocumentManagement\Infrastrucuture\DataAccess\ViiadDbContext.cs:line 33
   at DocumentManagement.Infrastrucuture.DataAccess.ViiadDbContext..ctor() in C:\Users\sbossbaly\Desktop\DocumentManagement\DocumentManagement\Infrastrucuture\DataAccess\ViiadDbContext.cs:line 20
   at DocumentManagement.Infrastrucuture.DataAccess.UnitOfWork..ctor() in C:\Users\sbossbaly\Desktop\DocumentManagement\DocumentManagement\Infrastrucuture\DataAccess\UnitOfWork.cs:line 30
   at Castle.Proxies.UnitOfWorkProxy7ad0e0e386ba4bc8ae9c5cab7065bd6c..ctor(IInterceptor[] )
  ----> System.NullReferenceException : Object reference not set to an instance of an object.

0 个答案:

没有答案