ayende/rhino-mocks

Stubs not returning proper Instance

Closed this issue · 2 comments

The following code will generate a runtime exception in Rhino Mocks

Previous method 'Dog.get_Active();' requires a return value or an exception to throw.

When I take Virtual off of the dog properties then the stub for my Dao just returns a newed up Dog object with default values not the one I specified.

I work around using MockRepository.GenerateStub() works however either should work really.

public class Dog
{
public virtual int Speed { get; set; }
public virtual bool Active { get; set; }
}
public interface IDogDao
{
Dog GetDog();
}
public class DogDao : IDogDao
{
public Dog GetDog() { throw new NotImplementedException(); }
}
public class MyService
{
public IDogDao DogDao { get; set; }
public void Manipulate()
{
Dog dog = DogDao.GetDog();
if (dog.Active)
{
dog.Speed++;
}
else
{
dog.Speed = 0;
}
}
}
public class MyService_test
{
[Test]
public void Manipulate_active_dog()
{
var dog = new Dog() {Active = true, Speed = 1};
var mocks = new MockRepository();
var dao = mocks.Stub();
dao.Stub(x => x.GetDog()).Return(dog);
MyService svc = new MyService() {DogDao = dao};
svc.Manipulate();
Assert.AreEqual(2, dog.Speed);
}
}

See also: http://groups.google.com/group/rhinomocks/browse_thread/thread/3576f7c702cf8699/3386333d305625b5#3386333d305625b5

This does not appear to be a bug.

Using Record/Replay you must move from Record state to Replay state, which you code is not doing.

Adding the following line immediately preceding svc.Manipulate() and your code above will work just fine.

mocks.ReplayAll()

you are right, thanks for your help Tim. It was my incorrect usage that was causing this behavior.