I'm learning Rhino Mocks

And don't know how to mock factory: I have a IViewModelFactory interface which is used by IOC

public interface IViewModelFactory
{
  T Create<T>() where T : IViewModel;
  T Create<T>(int Id) where T : IViewModel;
}

Currently I create mock with:

var _viewModelFactory = MockRepository.GenerateStub<IViewModelFactory>();
   viewModelFactory.Stub(x => x.Create<ViewModel1>())
                       .Return(new ViewModel1());

The ViewModel1 is a class like:

public class ViewModel1:BaseViewModel,IViewModel
{
  private int _id;
  public int ID
  {
    get { return _id;}
    set {
      if (_id==value) return;
      _id= value;
      RaisePropertyChanged(()=>ID)
    }
  }

  public ViewModel1()
  {
    ID=0;
  }

  public ViewModel1(int id)
  {
    ID=id;
  }
}

And this works for

  _viewModelFactory.Get<ViewModel1>();

But don't know how to create Stub for like:

  _viewModelFactory.Get<ViewModel1>(25);

Is that possible to mock?

有帮助吗?

解决方案

Let's see if I understood your question.. You have different solutions:

If you already know the Id that is going to be used you can do this:

var _viewModelFactory = MockRepository.GenerateStub<IViewModelFactory>();
var id = 1;
viewModelFactory.Stub(x => x.Create<ViewModel1>(id))
                   .Return(new ViewModel1(id));

If you don't know the id but you don't care about which one is going to be used because you will always return your viewmodel with the same id, you can do this:

var _viewModelFactory = MockRepository.GenerateStub<IViewModelFactory>();
viewModelFactory.Stub(x => x.Create<ViewModel1>(0))
                   .IgnoreArguments()
                   .Return(new ViewModel1(10));

If you want to create a viewmodel with the id that you get even though you don't know it while defining the test:

var _viewModelFactory = MockRepository.GenerateStub<IViewModelFactory>();
viewModelFactory.Stub(x => x.Create<ViewModel1>(Arg<int>.Is.Anything))
                   .Return(null)
                   .WhenCalled(x => {
                       var id = (int)x.Arguments[0];
                       x.ReturnValue = new ViewModel1(id);
                    });

NOTE: I can't test the code right now, but I think it should work!

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top