本文共 2129 字,大约阅读时间需要 7 分钟。
为了启用Mockito对静态方法的支持,您需要升级项目的依赖版本。以下是更新后的Maven依赖配置:
org.mockito mockito-core 3.6.28 test org.mockito mockito-inline 3.6.28 test org.mockito mockito-junit-jupiter 3.4.0 test
以下是一个简单的示例,展示如何使用Mockito来模拟静态方法:
public class MysteryBox { public static Optional mystery(String codeWord) { // 待实现 }} public class HaplessUser { public Mystery unleashMystery(String magicSpell) { Mystery om = MysteryBox.amaze(magicSpell); return om.orElseThrow(() -> new FailureToAmazeException("The box was empty")); }} 在单元测试类中,使用Mockito来模拟静态方法:
@Test@DisplayName("应在失败揭开谜团时抛出异常")void testUncoverMysteries() { try (MockedStatic mb = Mockito.mockStatic(MysteryBox.class)) { mb.when(() -> MysteryBox.amaze(any(String.class))).thenReturn(Optional.empty()); assertThrows(FailureToAmazeException.class, () -> subjectUnderTest.unleashMystery("Abracadabra")); }} 在同一个测试类中,多个测试方法可能需要模拟同一个静态方法时,可能会遇到以下异常:
org.mockito.exceptions.base.MockitoException: For xx.xxxx.util.SpringUtil, static mocking is already registered in the current thread
为了解决这个问题,可以采取以下步骤:
@TestInstance(PER_CLASS)@ExtendWith(MockitoExtension.class)public class KonfigurationCopyServiceTest { @InjectMocks private EKonfigurationCopyServiceImpl konfigurationCopyServiceImpl; @MockBean private FileProcessRecordServiceImpl fileProcessRecordService; @BeforeAll public void setUp() { MockedStatic mockSpringUtil = Mockito.mockStatic(SpringUtil.class); mockSpringUtil.when(() -> SpringUtil.getActiveProfile()).thenReturn("dev"); } @BeforeEach public void init() { // 其他方法的模拟 } @Test void test1() { // 测试方法内容 } @Test void test2() { // 测试方法内容 }} 通过以上方法,您可以轻松地在测试类中使用Mockito来模拟静态方法。记得在多个测试方法中使用静态方法时,确保在每个测试方法开始时重新初始化静态 mock,以避免上述异常。
转载地址:http://fbffk.baihongyu.com/