You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Mockito:根据方法调用次数切换抛出的异常

解决方法:按调用次数抛出不同异常

嘿,这个需求其实很常见,问题大概率出在你的计数器作用域不对——如果计数器是方法里的局部变量,每次调用都会重置,自然永远触发不了后面的异常。我给你几个可行的修改方案:

1. 实例方法(非线程安全)

如果你的方法是实例方法,每个对象实例独立计数,用实例变量来维护调用次数即可:

public class MyService {
    // 实例变量:每个对象实例单独计数
    private int callCount = 0;

    public void myMethod() throws FirstException, SecondException {
        callCount++;
        if (callCount <= 5) {
            throw new FirstException("这是前5次调用抛出的异常");
        } else {
            throw new SecondException("这是第6次及以后调用抛出的异常");
        }
    }
}

关键说明:

  • callCount定义在方法外部,作为类的成员变量,这样每次调用方法时都会保留之前的计数
  • 每次进入方法先递增计数器,再判断抛出哪种异常

2. 静态方法(非线程安全)

如果是静态方法,需要用静态变量来共享计数:

public class MyService {
    // 静态变量:所有实例共享同一个计数
    private static int staticCallCount = 0;

    public static void myStaticMethod() throws FirstException, SecondException {
        staticCallCount++;
        if (staticCallCount <= 5) {
            throw new FirstException("静态方法前5次调用的异常");
        } else {
            throw new SecondException("静态方法第6次及以后的异常");
        }
    }
}

3. 线程安全版本

如果你的方法会被多线程调用,普通的计数器会出现线程安全问题,建议用AtomicInteger来保证原子性:

import java.util.concurrent.atomic.AtomicInteger;

public class ThreadSafeService {
    // 原子类计数器:线程安全的计数方式
    private AtomicInteger threadSafeCount = new AtomicInteger(0);

    public void threadSafeMethod() throws FirstException, SecondException {
        // 原子性递增并获取当前值
        int currentCount = threadSafeCount.incrementAndGet();
        if (currentCount <= 5) {
            throw new FirstException("线程环境下前5次调用的异常");
        } else {
            throw new SecondException("线程环境下第6次及以后调用的异常");
        }
    }
}

核心要点总结:

  • 绝对不能把计数器定义在方法内部(局部变量),否则每次调用都会重置为初始值
  • 根据方法类型(实例/静态)选择对应作用域的计数器变量
  • 多线程场景必须使用线程安全的计数工具,避免计数混乱

内容的提问来源于stack exchange,提问作者raullalves

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 10:37:03