use mockito to stub final method [duplicate]

*爱你&永不变心* 提交于 2019-12-10 11:26:00

问题


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>


来源:https://stackoverflow.com/questions/21092935/use-mockito-to-stub-final-method

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!