使用
引入依赖
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>3.8.0</version>
</dependency>
代码实现
import org.mockito.MockedStatic;
import org.mockito.Mockito;
public class TestMockito {
public static void main(String[] args) {
// testMockNormalMethod();
// testMockDefaultMethod();
testMockStaticMethod();
}
/**
* mock 静态方法
*/
private static void testMockStaticMethod() {
//高版本3.4.0才支持
try (MockedStatic<PersonUtil> mockStatic = Mockito.mockStatic(PersonUtil.class);) {
mockStatic.when(() -> PersonUtil.checkParam()).thenReturn(false);
System.out.println(PersonUtil.checkParam());
}
}
/**
* mock java8的默认方法
*/
private static void testMockDefaultMethod() {
PersonServiceImpl personService = Mockito.spy(PersonServiceImpl.class);
Mockito.when(personService.checkParam(Mockito.any())).thenReturn(true);
personService.savePerson(new Object());
}
/**
* mock正常方法
*/
private static void testMockNormalMethod() {
PersonServiceImpl personService = Mockito.mock(PersonServiceImpl.class);
Mockito.when(personService.getPerson(Mockito.any())).thenReturn("lisi");
System.out.println(personService.getPerson("abc"));
}
interface PersonService {
default boolean checkParam(Object obj) {
System.out.println("check param: " + obj);
return false;
}
}
static class PersonServiceImpl implements PersonService {
public Object getPerson(String name) {
return name;
}
public void savePerson(Object obj) {
boolean check = checkParam(obj);
if (check) {
System.out.println("save person success");
} else {
System.out.println("save person fail");
}
}
}
static class PersonUtil {
public static boolean checkParam() {
throw new RuntimeException("check error");
}
}
}
总结
- mock默认方法需要使用 spy 方法
- mock静态方法需要添加如下依赖(版本必须为 3.4.0 及以上),不然会报错
Exception in thread "main" 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.
at com.imooc.TestMockito.testMockStaticMethod(TestMockito.java:19)
at com.imooc.TestMockito.main(TestMockito.java:11)
添加依赖为<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-inline</artifactId>
<version>3.8.0</version>
</dependency>