NiladriBose
NiladriBose

Reputation: 1905

Rhino mocks generics issue

I have an interface that I need to mock -

 public interface IRepositoryCachable  
 {
     IEnumerable<T> All<T>() where T : ICacheEntity;
     void Delete<T>(T item) where T : ICacheEntity;
     void Add<T>(T item) where T : ICacheEntity;
     void Update();
     T SingleOrDefault<T>(Func<T, bool> predicate) where T : ICacheEntity;
     IEnumerable<T> Find<T>(Func<T, bool> predicate) where T : ICacheEntity;
 }

Here is my test -

var repo = MockRepository.GenerateMock<IRepositoryCachable>();
repo.Expect(x => x.Add(Arg<ICacheEntity>.Is.Anything));

testClass = new testclass(repo);

testClass.Add;

repo.VerifyAllExpectations();

testClass.Add calls repo.Add. But in VerifyAllExpectation(); it barfs stating that Add was not called.

Code for test class - pseudo -

public class TestClass
{
    public void Add()
    {
         _repo.Add( new CacheEntity());
    }
}

What Am I doing wrong?

Upvotes: 1

Views: 1247

Answers (4)

giltanis
giltanis

Reputation: 487

What is happening here I think is that you are setting up an expectation for the method Add to be called but this method is distinct from Add which is the method you are really calling.

In short either change you expectation to:

repo.Expect(x => x.Add(Arg<CacheEntity>.Is.Anything));

Or change your non-test code to: _repo.Add<ICacheEntity>(new CacheEntity());

I am assuming you will not want to do the second since you put a generic parameter on that method and the only reason to do that is because you need to have the parameter be typed to the concrete type.

Upvotes: 0

jason
jason

Reputation: 241641

Why are you testing implementation details (what was called?) instead of behavior (that it was added to a database, or that a cached entity was returned, or whatever)?

Upvotes: 1

PatrickSteele
PatrickSteele

Reputation: 14677

Use GenerateStub instead of GenerateMock. Stubs are usually used for interfaces. I usually only use mocks when I'm mocking out actual class members.

Upvotes: 0

Phil Sandler
Phil Sandler

Reputation: 28016

This line seems suspect:

testClass.Add; 

Should a parameter be passed to this method? I don't even see how this can compile to be honest.

Upvotes: 0

Related Questions