Search code examples
javajunitmockitopowermockito

How can i stub Instant object using powermock


Is there a possibility to stub Instant object using Powermock? Powermock has the capability to mock final/static classes/methods.

I wanted something like :

Instant instant = PowerMockito.mock(Instant.now().getClass());
when(instant.getEpochSecond()).thenReturn(76565766587L);

i would need this mocking to be used elsewhere within my service class where i insert into table giving the time of that instant.

Thanks in advance!!


Solution

  • Yes, it is.

    My dependencies:

         <dependency>
             <groupId>org.powermock</groupId>
             <artifactId>powermock-module-junit4</artifactId>
             <version>2.0.4</version>
             <scope>test</scope>
         </dependency>
         <dependency>
                <groupId>junit</groupId>
                <artifactId>junit</artifactId>
                <version>4.12</version>
                <scope>test</scope>
          </dependency>
           <dependency>
                <groupId>org.mockito</groupId>
                <artifactId>mockito-core</artifactId>
                <version>2.28.2</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-api-mockito2</artifactId>
                <version>2.0.4</version>
                <scope>test</scope>
            </dependency>
            <dependency>
                <groupId>org.powermock</groupId>
                <artifactId>powermock-core</artifactId>
                <version>2.0.4</version>
                <scope>test</scope>
          </dependency>
    

    And my JUnit:

    @RunWith(PowerMockRunner.class)
    @PrepareForTest({Instant.class})
    public class InstantTest {
    
        public InstantTest() {
        }
    
        private Instant mock;
    
        @Before
        public void setUp() {
            PowerMockito.mockStatic(Instant.class);
            mock = PowerMockito.mock(Instant.class);
            PowerMockito.when(Instant.now()).thenReturn(mock);
        }
    
        @Test
        public void test() {
            Mockito.doReturn(76565766587L).when(mock).getEpochSecond();
            assertEquals(76565766587L, Instant.now().getEpochSecond());
        }
    }
    

    This code works, but IMHO insert into table is about Integration Test, not Unit Test so you need an embedded or testcontainers database and a roundtrip test where you really write data and read it again.