1、新建maven项目
2、pom文件中添加如下依赖(使用的是最新的版本)
注:此处使用junit5.3.2,使用junit4.1.2亦可
<dependencies>
<!-- https://mvnrepository.com/artifact/org.mockito/mockito-core -->
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>2.23.4</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.junit.jupiter</groupId>
<artifactId>junit-jupiter-api</artifactId>
<version>5.3.2</version>
<scope>test</scope>
</dependency>
</dependencies>
3、在src/test/java下创建测试类(注意是在test目录下!)
在main目录下建立测试类会找不到依赖!
原因如下:mockito依赖的Scope为Test,如果需要在main目录下使用,改为Compile即可。(测试类通常写在test环境下)
4、MyTest.java
import org.junit.jupiter.api.Test;
import java.util.LinkedList;
import static org.mockito.Mockito.*;
public class MyTest {
@Test
public void test(){
//You can mock concrete classes, not just interfaces
LinkedList mockedList = mock(LinkedList.class);
//stubbing
when(mockedList.get(0)).thenReturn("first");
when(mockedList.get(1)).thenThrow(new RuntimeException());
//following prints "first"
System.out.println(mockedList.get(0));
//following throws runtime exception
System.out.println(mockedList.get(1));
//following prints "null" because get(999) was not stubbed
System.out.println(mockedList.get(999));
//Although it is possible to verify a stubbed invocation, usually it's just redundant
//If your code cares what get(0) returns, then something else breaks (often even before verify() gets executed).
//If your code doesn't care what get(0) returns, then it should not be stubbed. Not convinced? See here.
verify(mockedList).get(0);
}
}
5、运行结果
6、其他样例
参见:http://static.javadoc.io/org.mockito/mockito-core/2.9.0/org/mockito/Mockito.html