user101010101
user101010101

Reputation: 1659

Rhino Mock using an expect on 'new' method call

Is it possible to do some form of expect NEW in rhino mock.

Example:

public void ToBeTested()
{
     ClassForExmaple classForExample = new ClassForExample();

     //Other logic.....
}

So I want my unit test to call ToBeTested(), but when the new ClassForExample is called I want it to return a mocked version.

Upvotes: 1

Views: 349

Answers (2)

Baz1nga
Baz1nga

Reputation: 15579

I have not worked with Rhino mock and I am not sure if this is something that is supported by RhinoMock but the fact that the control of creation of the object is embedded within the method violates the principles of DI/IOC and thus is harder to test.. Ideally the class should have been injected to the method either through the constructor of the containing class or to the method itself..

thus

class A
{
    IClassForExample _classForExample;
    public A(IClassForExample classForExample)
    {
      _classForExample=classForExample;
    }
    public void ToBeTested()
    {
         var classForExample = _classForExample;

         //Other logic.....
    }
}

Does RhinoSupport extending a non-abstract/interface class - a question I am not sure but I am sure it can mock the interface.

Upvotes: 1

Zonko
Zonko

Reputation: 3693

No, it's not possible, for the same reason you cannot expect static things : it is not called on an instance.

If you want to use a mock for an object that is built within your tested code, you should have something like this :

internal virtual ClassForExample NewClassForExempe()
{
    return new ClassForExample();
}

and then mock this method in your test.

Note : I put the method internal assuming you have rhino mocks declared in InternalsVisibleToAttribute of your class. Otherwise you'll have to make it public.

Upvotes: 0

Related Questions