场景
很多功能类依赖一个基础的Proxy,Proxy是一个单例,Proxy负责跟第三方通信,自测试时没有通信环境。此时需要为各功能类写测试用例,此时就需要需要mock一下这个Proxy,以便测试基于Proxy的各种功能类。
环境
1、JDK21
2、Window11
maven配置
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.13.2</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>org.mockito</groupId>
<artifactId>mockito-core</artifactId>
<version>5.14.0</version>
<scope>test</scope>
</dependency>
示例代码
1、Proxy
public class Proxy {
private static final Proxy proxy = new Proxy();
public static Proxy getInstance() {
return proxy;
}
public String sendExpression(String cmd) {
return "-1";
}
}
2、Func
public class Func {
public String getA() {
return Proxy.getInstance().sendExpression("A");
}
public String getB() {
return Proxy.getInstance().sendExpression("B");
}
}
3、Test
import static org.junit.Assert.assertEquals;
import static org.mockito.Mockito.*;
import cn.lifetool.app.api.Func;
import cn.lifetool.app.api.Proxy;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.MockedStatic;
import org.mockito.Mockito;
import org.mockito.junit.MockitoJUnitRunner;
@RunWith(MockitoJUnitRunner.class) // 使用Mockito的JUnit运行器
public class ATest {
@Test
public void testMethodWithSingleton() {
// 创建类的模拟实例
Proxy mp = mock(Proxy.class);
// 与第三方通信的方法进行打桩
when(mp.sendExpression("A")).thenReturn("AAA");
when(mp.sendExpression("B")).thenReturn("BBB");
// 使用Mockito的mockStatic来模拟D类的静态获取实例方法(如getInstance)
try (MockedStatic<Proxy> mockedStatic =
Mockito.mockStatic(Proxy.class)) { // 使用try-with-resources管理静态mock
// 设置当调用getInstance()时返回模拟的mock实例
mockedStatic.when(Proxy::getInstance).thenReturn(mp);
Func func = new Func();
assertEquals(func.getA(), "AAA"); // 根据业务逻辑断言
assertEquals(func.getB(), "BBB"); // 根据业务逻辑断言
// 验证方法是否被调用
verify(mp, times(1)).sendExpression("A"); // 验证Method被调用x次
verify(mp, times(1)).sendExpression("B"); // 验证Method被调用x次
} // 在此范围内,静态mock生效,超出后恢复
}
}