Tag Archives: mock final

Mockito can’t solve the problem of mockfinal class

Geeks, please accept the hero post of 2021 Microsoft x Intel hacking contest>>>

mockito is a very common testing tool. In the process of using it, you may encounter the following problems:

Mockito cannot mock/spy because : - final class

The problem recurred

The Maven configuration that introduces this dependency to the project is as follows:

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-core</artifactId>
  <version>3.3.3</version>
</dependency>

The test code is as follows:

package com.pkslow.basic;

import org.junit.Assert;
import org.junit.Test;

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

public class MockitoTest {

    public static final class FinalPumpkin {
        public String getName() {
            return "pkslow.com";
        }

    }

    @Test
    public void test() {
        FinalPumpkin pumpkin = mock(FinalPumpkin.class);
        when(pumpkin.getName()).thenReturn("www.pkslow.com");
        Assert.assertEquals("www.pkslow.com", pumpkin.getName());
    }
}

The error information is as follows:

org.mockito.exceptions.base.MockitoException: 
Cannot mock/spy class com.pkslow.basic.MockitoTest$FinalPumpkin
Mockito cannot mock/spy because :
 - final class

This is because the lower version of mockito cannot be mock final class

Solution:

Change the version of mockito , and modify the Maven dependency as follows:

<dependency>
  <groupId>org.mockito</groupId>
  <artifactId>mockito-inline</artifactId>
  <version>3.3.3</version>
</dependency>

Rerun test, problem solved


Welcome to pumpkin www.pkslow.com Get more wonderful articles

welcome to WeChat official account < pumpkin speak slowly >, Will continue to update for you

read more and share more; Write more and organize more