无法发布模拟 - Mockito

问题描述 投票:0回答:4

我正在尝试从 Mockito 版本 1.0.19 升级到 4.0.0 并使用 Junit 5,因为我无法在旧版本的 mockito 中模拟静态。我收到“无法发布模拟”错误..

请告诉我,迁移时需要注意什么。

public class RefreshTableSchedulerTest {

    @Mock
    ConfigRepository configRepository;

    @InjectMocks
    RandomScheduler randomScheduler;

    @BeforeEach
    public void setUp() throws Exception {
        MockitoAnnotations.initMocks(this);
        setReflectionUtils(randomScheduler);

    }

@Test
    public void testRefreshTableWithOutDelay() {
    // our trestcases

    }

随机调度器

@Configuration
@EnableScheduling
public class RandomScheduler {

@Scheduled(fixedDelayString = "${schedule.refresh.table.job.in.ms:1800000}")
    public void execute() {
    //fetch data from table A
    //inserts data to Table B using timestamps got from Table A
    //updates timestamp of Table A
    }
java spring-boot mockito junit5
4个回答
0
投票

如果您尝试使用mockito模拟静态类,则首先需要以下依赖项。如果您尝试在没有此依赖项的情况下模拟静态类,它将抛出该错误

<dependency>
    <groupId>org.mockito</groupId>
    <artifactId>mockito-inline</artifactId>
    <scope>test</scope>
</dependency>

然后使用

模拟静态类
MockedStatic<YourStaticClass> yourStaticClass = mockStatic(YourStaticClass.class)

还要确保您在 pom 中是否使用了正确的依赖项


0
投票
当您的依赖项不一致时,可能会发生

Failed to Release mocks
。由于您使用的是 Spring Boot,请确保不要更改主要的 Mockito 版本,而是使用
spring-boot-starter-test
和 Spring Boot 父级的正确版本,这将带来包括 Mockito 在内的对齐依赖项集。


0
投票

尝试在测试类顶部添加

@ExtendWith(MockitoExtension.class)
并从
MockitoAnnotations.initMocks(this);
方法中删除
setUp


0
投票

就我而言,我在 Android 上遇到了类似的错误。原因是以下问题:https://github.com/mockito/mockito/issues/2302

我按照问题中的建议解决这个问题:可调试版本。

© www.soinside.com 2019 - 2024. All rights reserved.