Mocking a private constructor

后端 未结 2 679
天涯浪人
天涯浪人 2021-01-05 06:51

The Site class is provided to me by an external team and has a private constructor.

public class Site
{
   int id;
   String br         


        
2条回答
  •  一个人的身影
    2021-01-05 07:07

    As an alternate approach, there's a way to compatibly alter their API if you can get management to back you. Instead of hiding the network lookups in the getSite() method, externalize them into a SiteLookupStrategy:

    public class SiteUtil {
        private static SiteLookupStrategy strategy = new DefaultSiteLookupStrategy();
    
        public static Site getSite(int siteNum) {
            return strategy.lookup(siteNum);
        }
    
        public static void setLookupStrategy(SiteLookupStrategy strategy) {
            SiteUtil.strategy = strategy;
        }
    }
    

    This way, for testing, you could inject your own (mocked) strategy, but existing clients of the code would not need to be changed. (This also has the advantage of making the lookup itself easier to test for that group.)

提交回复
热议问题