我如何使用powermock对即时对象进行存根

问题描述 投票:0回答:2

是否有可能使用Powermock存入Instant对象?Powermock具有模拟最终/静态类/方法的能力。

我想要类似的东西:

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

我将需要在我的服务类中的其他地方使用此模拟,并在其中插入表中给出该时刻的时间。

提前感谢!

java junit mockito powermockito
2个回答
1
投票

是,是。

我的依赖项:

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

此代码有效,但是将IMHO插入表中是关于集成测试,而不是单元测试,因此您需要一个嵌入式或testcontainers数据库以及一个往返测试,在此您可以真正写数据并再次读取它。


0
投票

您可以这样做

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

您也可以使用BDDMockitoBDDMockito.given(Instant.now()).willReturn(instant);

© www.soinside.com 2019 - 2024. All rights reserved.