如何使用Rhino Mocks存根ninject的IKernel?

时间:2010-06-19 20:57:23

标签: c# rhino-mocks ninject

var mocks = new MockRepository();
var access = new Access();
access.ShowRepository = _mocks.Stub<IShowRepository>();
access.ShowRepository.Stub(x => x.GetShows()).Return(new List<Show>());
var kernel =_mocks.Stub<IKernel>();
kernel.Stub(x => x.Get<Access>()).Return(access);

抛出ArgumentNullException:

  

消息:值不能为空。
  参数名称:source

堆栈跟踪:    在System.Linq.Enumerable.Cast [TResult](IEnumerable source)    在Ninject.ResolutionExtensions.Get [T](IResolutionRoot root,IParameter []参数)    在C:\ Users \ Dave \ Documents \ Visual Studio 2010 \ Projects \ Gigatube \ MediaMover.Unit.Tests \ ViewModelTests \ OptionsViewModelTests.cs中的MediaMover.Unit.Tests.ViewModelTests.OptionsViewModelTests.b__1(IKernel x)中:第33行    在Rhino.Mocks.RhinoMocksExtensions.Expect [T,R](T mock,Function 2 action) at Rhino.Mocks.RhinoMocksExtensions.Stub[T,R](T mock, Function 2 action)    在C:\ Users \ Dave \ Documents \ Visual Studio 2010 \ Projects \ Gigatube \ MediaMover.Unit.Tests \ ViewModelTests \ OptionsViewModelTests.cs:第33行的MediaMover.Unit.Tests.ViewModelTests.OptionsViewModelTests.Initialize()中

1 个答案:

答案 0 :(得分:1)

我能够解决这个问题,我必须创建一个测试模块和一个测试提供程序,然后通过这些模块传递我的模拟。

class DbAccessProvider : Provider<Access>
    {
        public Access DbAccess { get; set; }
        protected override Access CreateInstance(IContext context)
        {
            return DbAccess;
        }
    }

class TestModule : NinjectModule
    {
        public DbAccessProvider DbAccessProvider { get; set; }
        public override void Load()
        {
            Bind<Access>().ToProvider(DbAccessProvider);
        }
    }

这是我测试中的SetUp:

access = new Access();
access.SettingsRepository = MockRepository.GenerateStub<ISettingsRepository>();
access.ShowRepository = MockRepository.GenerateStub<IShowRepository>();
access.SettingsRepository.Stub(x => x.GetById(1)).Return(_settings);
DbAccessProvider dbAccessProvider = new DbAccessProvider();
dbAccessProvider.DbAccess = access;
TestModule testModule = new TestModule();
testModule.DbAccessProvider = dbAccessProvider;
var kernel = new StandardKernel(testModule);
target = new OptionsViewModel(kernel);