Mocking Factory with Arguments

I study Rhino Mocks

And I don't know how to taunt the factory: I have an IViewModelFactory interface that is used by IOC

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

I am currently creating a mock with:

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

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 it works for

  _viewModelFactory.Get<ViewModel1>();

But I don’t know how to create a Stub for:

  _viewModelFactory.Get<ViewModel1>(25);

Is it possible to make fun of?

+4
source share
1 answer

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

If you already know the Id 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 do not know the identifier, but you do not care about which one will be used, because you will always return your view model with the same identifier, you can do this:

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

viewmodel , , :

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);
                    });

. , , !

+3

All Articles