2

We have a test scenario in which we have a base class that news up an instance of all Injectible dependencies for each test (in the [SetUp] method). However, no matter what I do, stubs or expectations set in one test are being retained in subsequent tests. Just running the following twice, I see that when I call

_someStub = MockRepository.GenerateMock<T>();

each time, the same instance is returned, even if I set it to null first, and even if I use a new instance of MockRepository like so:

repo = new MockRepository();
_someMock = repo.Mock<T>();
_someMock.Stub(t => t.SomeMethod()).Return(someObject);

I have tried doing:

_someMock.BackToRecord();
_someMock.Replay();
_someMock.Stub(t => t.SomeMethod()).Return(someOtherObject);

but for the second test, SomeMethod always returns someObject instead of someOtherObject.

I hope this makes sense. Simplified sample code below.

public MockTestBase  {
     protected ISomeClass _someMock;

     [SetUp]
     protected void DoSetup() {
          _someMock = null; //just trying this, makes no difference
          _someMock = MockRepository.GenerateStub<ISomeClass>(); //returns Castle.Proxies.ISomeClassxxxxxxxxxxx every time
     } 
}

public ControllerTest : MockTestBase {
    protected MyController GetController() {
         return new MyController(_someMock );
     } 

     [Test]
     public void TestOne() {
          var object = new SomeObject() { SomeProperty = "1" };
          _someMock.Stub(t => SomeMethod()).Return(object);
          //execute test
     }

     [Test]
     public void TestTwo() {
          var object = new SomeObject() { SomeProperty = "2" };
          _someMock.Stub(t => SomeMethod()).Return(object);  
          //execute test
          //SomeMethod() returns object from TestOne
     }
}
sydneyos
  • 4,527
  • 6
  • 36
  • 53
  • http://stackoverflow.com/questions/770013 - Does this help? Where is the GetController() method invoked from ? Are you reusing the same instance across tests ? – Gishu May 23 '13 at 02:00
  • @Gishu - I have tried most of those things, but I will try Repeat.Any(). GetController is in a base class and each test calls it to get a new instance of the controller (not a reused instance). It just feels to me like this should not be necessary. If you create a whole new instance of a mock, it should not be carrying around previous expectations. Funky. – sydneyos Jun 19 '13 at 16:55
  • I have same problem, is there any final solution to this? – jumbo Mar 28 '17 at 08:21

0 Answers0