赞
踩
开发依赖 | 版本 |
---|---|
Spring Boot | 3.0.6 |
JDK | 20 |
<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静态方法,则会抛这个异常
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。