模拟私有构造函数 [英] Mocking a private constructor

查看:124
本文介绍了模拟私有构造函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

站点类由外部团队提供给我,并且具有私有构造函数。

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

public class Site
{
   int id;
   String brand;

   private Site(int id, String brand)
   {
      this.id = id;
      this.brand = brand;
   }
}

SiteUtil类(由团队控制)是

The SiteUtil class (controlled by team) is

public class SiteUtil
{
   public static Site getSite()
   {
     Site site;
     //Logic
     return site; 
   }
 }

getSite( )函数将其应用于需要网络调用的逻辑,因此需要对其进行模拟。它目前没有设置器(也许是为了保持与数据源的一致性,不太确定)

The data the getSite() function applies it logic on requires a network call, therefore it needs to be mocked. It doesn't have a setter currently (maybe to maintain consistency with the data source, not so sure)

我如下模拟

Site mockSite = new Site(1,"Google");
PowerMockito.when(SiteUtil.getSite(1)).thenReturn(mockSite);

上面的代码当然是在使用公共构造函数时编译的。
我读的解决方案是模拟 Site 对象的私有构造函数。但是,我对如何做到这一点不知所措(第一次编写单元测试!)

The code above of course dosent compile as I use the public constructor. The solution I read was to mock the private constructor of Site object. I'm however at a loss on how to do that (First time writing unit tests!)

推荐答案

假设您的代码可以访问只能通过吸气剂将其值设置为 id brand 的值,您只需模拟类 Site ,然后在您调用静态方法 SiteUtil.getSite()时返回此模拟,如下所示:

Assuming that your code accesses to the value of id and brand only through getters, you could simply mock your class Site then return this mock when you call the static method SiteUtil.getSite() as next:

// Use the launcher of powermock
@RunWith(PowerMockRunner.class)
public class MyTestClass {

    @Test
    // Prepare the class for which we want to mock a static method
    @PrepareForTest(SiteUtil.class)
    public void myTest() throws Exception{
        // Build the mock of Site
        Site mockSite = PowerMockito.mock(Site.class);
        // Define the return values of the getters of our mock
        PowerMockito.when(mockSite.getId()).thenReturn(1);
        PowerMockito.when(mockSite.getBrand()).thenReturn("Google");
        // We use spy as we only want to mock one specific method otherwise
        // to mock all static methods use mockStatic instead
        PowerMockito.spy(SiteUtil.class);
        // Define the return value of our static method
        PowerMockito.when(SiteUtil.getSite()).thenReturn(mockSite);

        ...
    }
}

这篇关于模拟私有构造函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆