本地开发环境说明
开发依赖版本Spring Boot3.0.6JDK20
pom.xml主要依赖
<dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-test</artifactId><scope>test</scope></dependency><!-- mock静态方法需要引入这个依赖 --><dependency><groupId>org.mockito</groupId><artifactId>mockito-inline</artifactId><scope>test</scope></dependency></dependencies>
写一个静态方法
packagecom.wen3.framework.junit.utils;publicclassDemoUtils{publicstaticStringhello(String name){returnString.join(",","hello", name);}}
单元测试
packagecom.wen3.framework.junit.statictest;importcom.wen3.framework.junit.utils.DemoUtils;importorg.apache.commons.lang3.RandomStringUtils;importorg.junit.jupiter.api.Assertions;importorg.junit.jupiter.api.Test;importorg.mockito.Mockito;importstaticorg.mockito.ArgumentMatchers.anyString;importstaticorg.mockito.Mockito.when;publicclassStaticTestextendsAssertions{@TestvoidtestHello(){// 测试没有mock的情况String name =RandomStringUtils.randomAlphabetic(10);String testResult =DemoUtils.hello(name);assertEquals("hello,"+name, testResult);// mock静态方法Mockito.mockStatic(DemoUtils.class);String valueMock =RandomStringUtils.randomAlphabetic(10);when(DemoUtils.hello(anyString())).thenReturn(valueMock);
testResult =DemoUtils.hello(name);assertEquals(valueMock, testResult);}}
报错
org.mockito.exceptions.base.MockitoException:
The used MockMaker SubclassByteBuddyMockMaker does not support the creation of static mocks
Mockito's inline mock maker supports static mocks based on the Instrumentation API.
You can simply enable this mock mode, by placing the 'mockito-inline' artifact where you are currently using 'mockito-core'.
Note that Mockito's inline mock maker is not supported on Android.
如果没有引入
mockito-inline
这个依赖,使用mock静态方法,则会抛这个异常
单元测试运行结果
本文转载自: https://blog.csdn.net/friendlytkyj/article/details/131021768
版权归原作者 太空眼睛 所有, 如有侵权,请联系我们删除。
版权归原作者 太空眼睛 所有, 如有侵权,请联系我们删除。