如何使用 powermock 存根即时对象



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

我想要这样的东西:

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

我需要在我的服务类中的其他地方使用这种模拟,在那里我插入到表中给出那个时刻的时间。

提前感谢!!

是的,是的。

我的依赖项:

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

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

你可以这样做

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

最新更新