开发者

Mocking - setting a property before calling the constructor

In RhinoMocks or Moq, can properties on an object be set before the constructor is 开发者_Go百科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?


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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜