我正在使用 Spring Boot 并在单元测试中尝试模拟该Files.delete(myFile.toPath())方法。
为此,我正在尝试使用该Mockito.mockStatic()方法。但是当我尝试使用它时,我的 IDE(IntelliJ IDEA)告诉我这个方法不存在。我读了这篇文章:https :
//asolntsev.github.io/en/2020/07/11/mockito-static-methods/
但它没有帮助我。
在我的 POM.xml 文件中有:
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.5.15</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-junit-jupiter</artifactId>
<version>3.5.15</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<version>2.2.6.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework.security</groupId>
<artifactId>spring-security-test</artifactId>
<scope>test</scope>
</dependency>
Run Code Online (Sandbox Code Playgroud)
请注意,我只放置了测试相关的依赖项,这不是我的整个 POM.xml 文件
在我的测试文件中,我放置了以下导入:
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.boot.test.mock.mockito.MockBean;
import org.springframework.test.context.junit4.SpringRunner;
Run Code Online (Sandbox Code Playgroud)
同样,这只是与测试相关的导入。
您知道为什么该Mockito.mockStatic()方法无法解决吗?
我正在使用 Spring Boot,在我的一个单元测试中,我需要模拟该Files.delete(somePath)函数。这是一个静态void方法。
我知道使用 Mockito 可以模拟 void 方法:
doNothing().when(MyClass.class).myVoidMethod()
Run Code Online (Sandbox Code Playgroud)
自 2020 年 7 月 10 日起,可以模拟静态方法:
try (MockedStatic<MyStaticClass> mockedStaticClass = Mockito.mockStatic(MyStaticClass.class)) {
mockedStaticClass.when(MyStaticClass::giveMeANumber).thenReturn(1L);
assertThat(MyStaticClass.giveMeANumber()).isEqualTo(1L);
}
Run Code Online (Sandbox Code Playgroud)
但我无法模拟静态无效方法,例如Files.delete(somePath).
这是我的 pom.xml 文件(仅测试相关依赖项):
doNothing().when(MyClass.class).myVoidMethod()
Run Code Online (Sandbox Code Playgroud)
有没有办法在不使用 PowerMockito 的情况下模拟静态 void 方法?
如果可能,这样做的正确语法是什么?