小编Ehr*_*kis的帖子

Mockito mockStatic 无法解析符号

我正在使用 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)

同样,这只是与测试相关的导入。

我的 IDE 显示的屏幕截图:
在此处输入图片说明

您知道为什么该Mockito.mockStatic()方法无法解决吗?

java spring unit-testing mockito spring-boot

4
推荐指数
1
解决办法
2424
查看次数

Mockito 使用 Mockito.mockStatic() 模拟静态 void 方法

我正在使用 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 方法?
如果可能,这样做的正确语法是什么?

java spring unit-testing mockito spring-boot

3
推荐指数
1
解决办法
4415
查看次数

标签 统计

java ×2

mockito ×2

spring ×2

spring-boot ×2

unit-testing ×2