【发布时间】:2021-02-04 09:04:06
【问题描述】:
我正在使用 Spring Boot,在我的一个单元测试中,我需要模拟 Files.delete(somePath) 函数。这是一个静态的 void 方法。
我知道使用 Mockito 可以模拟 void 方法:
doNothing().when(MyClass.class).myVoidMethod()
并且自 2020 年 7 月 10 日起,可以模拟静态方法:
try (MockedStatic<MyStaticClass> mockedStaticClass = Mockito.mockStatic(MyStaticClass.class)) {
mockedStaticClass.when(MyStaticClass::giveMeANumber).thenReturn(1L);
assertThat(MyStaticClass.giveMeANumber()).isEqualTo(1L);
}
但我无法模拟 Files.delete(somePath) 等静态 void 方法。
这是我的 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-core</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>
有没有办法在不使用 PowerMockito 的情况下模拟静态 void 方法?
如果可能,这样做的正确语法是什么?
【问题讨论】:
-
你添加 mockito-inline 作为依赖了吗?
-
是的,我做了,我将编辑我的问题以添加我的 POM.xml 文件。
标签: java spring spring-boot unit-testing mockito