use mockito to stub final method [duplicate]

2019-05-24 13:47发布

问题:

This question already has an answer here:

  • Final method mocking 7 answers

I need to use a mock who has a final method. So i use powermock but it does not work

class B {
    public final int nb() {
        return 4;
    }
}

@RunWith(PowerMockRunner.class)
@PrepareForTest(B.class)
public class Exemple extends TestCase {
    @Test
    public void test() { 
        B b = PowerMockito.mock(B.class);

        PowerMockito.when(b.nb()).thenReturn(5);

        final int actualState = b.nb();

        assertEquals(5, actualState);

    }   
}

if someone has a solution, thank you in advance

回答1:

Your example is fine, should work without any problem.

Tests Passed: 1 passed in 0,226 s

I have tested it with

<dependency>
    <groupId>junit</groupId>
    <artifactId>junit</artifactId>
    <version>4.11</version>
</dependency> 

<dependency>
    <groupId>org.powermock</groupId>
    <artifactId>powermock-module-junit4</artifactId>
    <version>1.5.2</version>
</dependency>