开发者

How to stub a static method?

I am working on a brownfield application and am currently refactoring part of it. I am trying to do this开发者_如何学运维 in a TDD fashion but am running into a problem. Part of the code I am testing does

var siteLanguages = from sl in SiteSettings.GetEnabledSiteLanguages() select sl.LanguageID;

where GetEnabledLanguages has the following signature

public static List<LanguageBranch> GetEnabledSiteLanguages();

it in turns calls data access code to retrieve the relevant information. Up untill now I have used a interface and DI to use a different stub implementation for these kind of dependencies during unit testing. But since the GetEnabledSiteLanguages method is static this will not work. What is the "correct" way to do it in this case?


you could create a object which implements an interface and inject an implementation of this into the class which uses the SiteSettings class. The interface declare the method with the same signature as the static method(s) you need to intercept. Then you could mock out the interface for tests and create a single implementation which delegates to the static method for the actual code:

public interface ISiteSettings
{
    public List<LanguageBranch> GetEnabledSiteLanguages()
}

public class ActualSiteSettings : ISiteSettings
{
    public List<LanguageBranch> GetEnabledSiteLanguages()
    {
         return SiteSettings.GetEnabledSiteLanguages();
    }
}

... in the dependent class:

public class DependentClass
{
    private ISiteSettings m_siteSettings;

    public DependentClass(ISiteSettings siteSettings)
    {
    m_siteSettings=siteSettings;
    }

    public void SomeMethod
    {
         var siteLanguages = from sl in m_siteSettings.GetEnabledSiteLanguages() select sl.LanguageID;
    }
}


What about making your method such as:

public static Func<List<LanguageBranch>> GetEnabledSiteLanguages = () => {
   //your code here
};

Now it becomes first class object (as Func delegate) and a stub can replace it


Look at Moles framework.


You can use tools like JustMock, TypeMock or moles. These tools allow you to mock everythings like static methods.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜