将mockito-core换成mockito-inline
org.mockito
mockito-inline
3.6.0
test
[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:54c0a9b0-7014-4afa-9d13-2664a4dd30e5
[En]
[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:837099e2-110f-4c3e-9a1e-6dba1681ed98
import java.time.LocalDate;
public class Utils {
public LocalDate getCurrentDate() {
return LocalDate.now();//now()为静态方法
}
}
创建单元测试类
@RunWith(MockitoJUnitRunner.class)
@SpringBootTest
@TestInstance(PER_CLASS)
class UtilsTest {
@Autowired
Utils utils;//注入待测试的类
@MockBean
MockedStatic localDateMockedStatic;
@BeforeAll
void setUp() {
localDateMockedStatic = mockStatic(LocalDate.class);//初始化静态类
}
@Test
public void testGetCurrentDate() {
LocalDate yearOf2000 = LocalDate.of(2000, 1, 1);
localDateMockedStatic.when(
() -> LocalDate.now())
.thenReturn(yearOf2000);
System.out.println(utils.getCurrentDate());
assertEquals(2000, target.getCurrentDate().getYear());
}
}
打印结果
main:2000-01-01
测试通过,打印的日期是 2000-01-01。
Mockito Mock 静态方法的弊端
在实际应用 Mockito 对静态方法进行 Mock 的时候,发现在多线程的时候失效,问题在于mockStatic只对当前线程的调用有效。
localDateMockedStatic = mockStatic(LocalDate.class);//初始化静态类
下面看个例子:
@Test
public void testGetCurrentDate() {
LocalDate yearOf2000 = LocalDate.of(2000, 1, 1);
localDateMockedStatic.when(
() -> LocalDate.now())
.thenReturn(yearOf2000);
System.out.println(Thread.currentThread().getName() + ":" + LocalDate.now());
Thread thread = new Thread(() ->
System.out.println(Thread.currentThread().getName() + ":" + LocalDate.now()));
thread.start();
thread.join();
}
打印结果:
main:2000-01-01
Thread-0:当前时间。
[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:1b9ef9a9-722f-4ab4-9561-ce0d97724327
[En]
[TencentCloudSDKException] code:FailedOperation.ServiceIsolate message:service is stopped due to arrears, please recharge your account in Tencent Cloud requestId:13441e9a-434f-448a-a532-778a4e58b3fa
Original: https://www.cnblogs.com/dhavin/p/16338455.html
Author: dhf123
Title: 静态方法单元测试
原创文章受到原创版权保护。转载请注明出处:https://www.johngo689.com/562867/
转载文章受原作者版权保护。转载请注明原作者出处!