Mocking a private constructor

后端 未结 2 670
天涯浪人
天涯浪人 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:15

    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);
    
            ...
        }
    }
    

提交回复
热议问题