在intellj中使用mockito(依赖maven)

1、新建maven项目

2、pom文件中添加如下依赖(使用的是最新的版本)

注:此处使用junit5.3.2,使用junit4.1.2亦可

    
        
        
            org.mockito
            mockito-core
            2.23.4
            test
        

        
            org.junit.jupiter
            junit-jupiter-api
            5.3.2
            test
        
    

3、在src/test/java下创建测试类(注意是在test目录下!)

在intellj中使用mockito(依赖maven)_第1张图片

在main目录下建立测试类会找不到依赖!

原因如下:mockito依赖的Scope为Test,如果需要在main目录下使用,改为Compile即可。(测试类通常写在test环境下)

在intellj中使用mockito(依赖maven)_第2张图片

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、运行结果

在intellj中使用mockito(依赖maven)_第3张图片

6、其他样例

参见:http://static.javadoc.io/org.mockito/mockito-core/2.9.0/org/mockito/Mockito.html

 

 

你可能感兴趣的:(java)