在intellj中使用mockito(依赖maven)

本文详细介绍了如何在Maven项目中配置并使用JUnit5和Mockito进行单元测试。从创建项目、添加依赖到编写测试代码,再到运行结果的展示,全程实战演示。适合初学者快速上手。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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

 

 

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值