Mr. Boy
Mr. Boy

Reputation: 63720

Mocking an object constructed inside a method call

I'm new to Rhino Mocks and mocking in C# though not in general. I'm writing unit tests for a class MyClasswhich internally creates other objects as private fields. I've unit tested those classes separately but not how MyClass interacts with them...

class MyClass
{
 public void Method1()
 {
  var o = new OtherClass();
  o.Method2();
  o.Method3();
 }
}

Note that I don't pass OtherClass as a ctor argument and I don't really want to... creating these objects is something the class does, I don't really want an external agent injecting them.

Does Rhino Mocks allow me to somehow mock OtherClass in this scenario from a unit test, so I can determine instances are created and interacted with correctly?

Upvotes: 1

Views: 725

Answers (2)

Old Fox
Old Fox

Reputation: 8725

No, Rhinomocks mocks doesn't support this capability. Rhinomocks/Moq/FakeItEasy/NSubstitute are all proxy based tools which means non of them are able to isolate your code without refactoring.

To be able to isolate without refactoring you need to use code weaving tools such as Typemock Isolator, Msfakes and etc...

Somehow it is not so popular in the community to combine 2 mocking frameworks in the same project, however when I was in the .net world I usually combine Rhinomocks and Msfakes together;

  • Rhinomocks as a default Mocking framework
  • Msfakes only where it is necessary(for regular cases Rhinomocks is better....); static/sealed and etc...

Upvotes: 1

Daniel
Daniel

Reputation: 174

Disclaimer I work at TypeMock.

It's very simple to fake a future Instance when using Typemock Isolator, actually it can be done in one line :

    var classUnderTest = new MyClass();
    // Faking future OtherClass 
    var fakeOther = Isolate.Fake.NextInstance<OtherClass>();

And you can read more about it here.

Upvotes: 1

Related Questions