gpt4 book ai didi

java - 使用 PowerMockito 在 JUnit5 中模拟静态方法

转载 作者:行者123 更新时间:2023-12-01 16:34:57 25 4
gpt4 key购买 nike

需要使用 JUnit5 和 PowerMockito 框架模拟静态方法的帮助。

Powermock junit5 and mockito2.x not working RunnerTestSuiteChunker not found

import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PowerMockIgnore;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import static org.mockito.Mockito.*;


@PrepareForTest(EnvironmentUtils.class)
@RunWith(PowerMockRunner.class)
public class RuleControllerTest {

@Before
public void setup() {
PowerMockito.mockStatic(EnvironmentUtils.class);
}


@Test
public void test_rule_create_rule() throws IOException {
when(EnvironmentUtils.isCF()).thenReturn(true);

}
}

和pom.xml

<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.4.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
<version>5.4.2</version>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-engine</artifactId>
<version>5.4.2</version>
<scope>test</scope>
</dependency>
<!-- https://mvnrepository.com/artifact/junit/junit -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-module-junit4</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.powermock</groupId>
<artifactId>powermock-api-mockito2</artifactId>
<version>2.0.2</version>
<scope>test</scope>
</dependency>

我从这里跟踪了 Junit5 示例,1) https://www.baeldung.com/junit-52) Junit5 mock a static method

但面临一个问题,我知道存在一个 issue对于带有 powermock 的 Junit5,但任何人都知道使用 powermock 使用 JUnit5 模拟静态方法的任何其他方法。

最佳答案

使用mockito v 3.4.0,我们可以简单地使用mockStatic()方法,而无需powermock库:

 try (MockedStatic mocked = mockStatic(Foo.class)) {
mocked.when(Foo::method).thenReturn("bar");
assertEquals("bar", Foo.method());
mocked.verify(Foo::method);
}

assertEquals("foo", Foo.method());

最新文档和示例: https://javadoc.io/static/org.mockito/mockito-core/3.5.10/org/mockito/Mockito.html#static_mocks

关于java - 使用 PowerMockito 在 JUnit5 中模拟静态方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61975300/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com