我如何使用 powermock 存根 Instant 对象

How can i stub Instant object using powermock

是否可以使用 Powermock 存根 Instant 对象? Powermock 能够模拟 final/static classes/methods.

我想要这样的东西:

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

我需要在我的服务 class 中的其他地方使用这个模拟,我在其中插入 table 给出那一刻的时间。

提前致谢!!

是的,是的。

我的依赖项:

     <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>

还有我的 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());
    }
}

此代码有效,但恕我直言,插入 table 是关于集成测试,而不是单元测试,因此您需要一个嵌入式或测试容器数据库以及一个真正写入数据并再次读取的往返测试。

你可以这样做

import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.springframework.boot.test.context.SpringBootTest;
import ru.apibank.delivery.service.publisher.runners.PowerMockTestRunner;

import java.time.Instant;

@SpringBootTest
@RunWith(PowerMockTestRunner.class)
@PrepareForTest(value = {Instant.class})
public class TestClass {

    @Test
    public void testInstant() {
        long epochSeconds = 76565766587L;
        Instant instant = Instant.ofEpochSecond(epochSeconds);

        PowerMockito.mockStatic(Instant.class);
        Mockito.when(Instant.now()).thenReturn(instant);

        Assert.assertEquals(epochSeconds, Instant.now().getEpochSecond());
    }
}

你也可以使用 BDDMockito BDDMockito.given(Instant.now()).willReturn(instant);