views:

138

answers:

2

In RhinoMocks or Moq, can properties on an object be set before the constructor is called?

I'm trying to test a method.

The class containing the method has some code in it's constructor which depends on some members being set, unfortunately there's no params in the constructor to set them so I must set them through a property. Is there any way to set this property before calling the constructor in RhinoMocks or Moq?

+5  A: 

How would that work? Setting a property on an object that does not yet exist? I think you should recognize that there is something wrong with the design of your class and try to change it so that it becomes more testable, for example by using dependency injection.

klausbyskov
A: 

This sounds strange: klausbyskov is probably right in that there's some design problem here.

Are these members set directly in the code? For example

protected string myField = "this and that";

public MyClass()
{
    if (myField == "this and that") { DoSomething(); }
}

If that's the case then the only way these members can be changed is if a subclass overrides them e.g. the constructor

public SubClass()
{
    myField = "something else";
}

will ensure that SubClass() has the field initialized to "something else". However, this will run after the constructor for MyClass().

I would carefully examine the need for any logic in your constructor. In general that's a bad idea; if you need to conditionally create members in an object, consider the Factory pattern instead.

Jeremy McGee