本地开发环境说明
开发依赖 | 版本 |
---|---|
Spring Boot | 3.0.6 |
JDK | 20 |
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>
写一个静态方法
package com.wen3.framework.junit.utils;
public class DemoUtils {
public static String hello(String name) {
return String.join(",", "hello", name);
}
}
单元测试
package com.wen3.framework.junit.statictest;
import com.wen3.framework.junit.utils.DemoUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.mockito.Mockito;
import static org.mockito.ArgumentMatchers.anyString;
import static org.mockito.Mockito.when;
public class StaticTest extends Assertions {
@Test
void testHello() {
// 测试没有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://www.toymoban.com/news/detail-765020.html
单元测试运行结果
文章来源地址https://www.toymoban.com/news/detail-765020.html
到了这里,关于【Junit】单元测试Mock静态方法的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!