2013-08-30 67 views
3

我有这样的事情:如何使用Rhino Mocks模拟受保护的计算只读属性?

public class SomeClass 
{ 
    protected ISomeInterface SomeProperty 
    { 
     get { return SomeStaticClass.GetSomeInterfaceImpl(); } 
    } 

    public void SomeMethod() 
    { 
     // uses SomeProperty in calculations 
    } 
} 

如何测试的someMethod,嘲讽使用犀牛制品SomeProperty?我正考虑获取访问者,使用IL重写访问者,只是返回模拟代理。听起来有多疯狂?

+2

我建议重构你的代码,以便将'ISomeInterface'注入到'SomeClass'中。现在,你的'SomeStaticClass'形式具有很强的依赖性,这很难有效地模拟。 –

+1

为什么财产首先受到保护? –

+0

不幸的是,这是一个不能改变的DLL的一部分(商业原因)。 –

回答

0

你不能模拟被测试的类,但只能依赖。因此,如果您使用某种工厂而不是SomeStaticClas并使用SomeClass的构造函数参数注入它,则可以模拟工厂类。

public class SomeClass 
{ 
    public SomeClass(ISomeInterfaceFactory factory) 
    { 
     this.factory = factory; 
    } 

    protected ISomeInterface SomeProperty 
    { 
     get { return factory.GetSomeInterface(); } 
    } 

    public void SomeMethod() 
    { 
     // uses SomeProperty in calculations 
    } 
} 

public interface ISomeInterfaceFactory 
{ 
    ISomeInterface GetSomeInterface(); 
} 
相关问题