Java 使用PowerMockito在JUnit5中模拟静态方法
需要使用JUnit5和PowerMockito框架模拟静态方法的帮助 和pom.xmlJava 使用PowerMockito在JUnit5中模拟静态方法,java,junit5,powermockito,junit5-extension-model,Java,Junit5,Powermockito,Junit5 Extension Model,需要使用JUnit5和PowerMockito框架模拟静态方法的帮助 和pom.xml <!-- https://mvnrepository.com/artifact/org.mockito/mockito-core --> <dependency> <groupId>org.mockito</groupId> <artifactId>mockito-core</artifactId> <ve
<!-- 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>
org.mockito
(二)
但是面对这样一个问题,我知道Junit5有一个使用powermock的现有版本,但是任何人都知道使用Junit5使用powermock模拟静态方法的任何其他方法。正如您的链接所建议的,您仍然不能直接用junit-5进行power Mock,仅仅因为有没有PowerMockRunner
(扩展)junit-5仍然可用
然而,在上面的代码中,可能出了问题的是这一行
when(EnvironmentUtils.isCF()).thenReturn(true);
在这里,请注意,您在使用mockito的时使用了(通过import static org.mockito.mockito.*;
)
相反,您必须使用PowerMockito
中的一个。所以
删除这一行import static org.mockito.mockito.*代码>
相反,添加这个<代码>导入静态org.powermock.api.mockito.PowerMockito.*
删除静态导入,它将正常工作,因为when()
调用指向Mockito
而不是PowerMock对于Mockito v3.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());
最新文档和示例:
您正在使用@Before,它是junit4注解。。Junit5有@beforeach/@BeforeAll(以适合您的要求为准)。另外,您对@Test的导入来自junit4,而不是junit5(应该是org.junit.jupiter.api.Test;)请参阅:。@Progman我在这里看到了一个明确的问题,以及他是如何解决的。我不同意你的评论:(
try (MockedStatic mocked = mockStatic(Foo.class)) {
mocked.when(Foo::method).thenReturn("bar");
assertEquals("bar", Foo.method());
mocked.verify(Foo::method);
}
assertEquals("foo", Foo.method());