2010-07-13 12 views
2

je suis arrivé cette méthode Moq vraiment cool qui feint mon GetService, ressemble à ceciMoq à Rhino - faux dépôt partiel

private Mock<IGetService<TEntity>> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new() 
{ 
    var mockGet = new Mock<IGetService<TEntity>>(); 
    mockGet.Setup(mock => mock.GetAll()).Returns(fakeList); 
    mockGet.Setup(mock => mock.Get(It.IsAny<int>())).Returns((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString())); 
    mockGet.Setup(mock => mock.Get(It.IsAny<Expression<Func<TEntity, bool>>>())).Returns((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression)); 

    return mockGet; 
} 

et d'utiliser cette ...

var fakeList = new List<Something>(); 
fakeList.Add(new Something { Whatever = "blah" }); 
//do this a buncha times 

_mockGetService = FakeGetServiceFactory(fakeList); 
_fakeGetServiceToInject = _mockGetService.Object; 

Comment puis-je jeter ceci dans Rhino.Mock?

Répondre

1

Quelque chose le long de ces lignes (désolé, je n'ai pas VS à portée de main, donc je ne peux pas tester):

private IGetService<TEntity> FakeGetServiceFactory<TEntity>(List<TEntity> fakeList) where TEntity : class, IPrimaryKey, new() 
{ 
    var mockGet = MockRepository.GenerateMock<IGetService<TEntity>>(); 
    mockGet.Expect(mock => mock.GetAll()).Return(fakeList); 
    mockGet.Expect(mock => mock.Get(Arg<int>.Is.Anything)).Do((int i) => fakeList.Find(fake => fake.Id.ToString() == i.ToString())); 
    mockGet.Expect(mock => mock.Get(Arg<Expression<Func<TEntity, bool>>>.Is.Anything)).Do((Expression<Func<TEntity, bool>> expression) => fakeList.AsQueryable().Where(expression)); 

    return mockGet; 
} 
+0

Sweeeet. C'est plein de victoire. Merci. – jeriley

+0

@jeriley: Je crois que cela va enregistrer 3 appels attendus, dont chacun doit être appelé dans l'ordre donné par le test. Je ne pense pas que ce soit ce que tu veux ici. Essayez d'utiliser des stubs à la place. J'ai essayé d'expliquer la différence dans un article de blog: http://mindinthewater.blogspot.com/2010/02/mocking-frameworks-stubs-vs-mocks.html –

+0

@Wim, vous n'avez pas besoin de les appeler dans l'ordre particulier. Je ne suis pas sûr comment le programme d'installation de simulation fonctionne, mais il est possible que ceux-ci doivent être remplacés par Stubs. – Grzenio