Powermockito 可以在非最终具体类中模拟最终方法吗?

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

假设我有一个非最终具体类,具有如下所示的最终方法。

public class ABC {
  public final String myMethod(){
      return "test test";
  }
}

当使用

myMethod()
junit
中调用它时,是否可以模拟
Powermockito
返回其他内容?谢谢你

java unit-testing powermock
2个回答
32
投票

这有效:

@RunWith(PowerMockRunner.class)
@PrepareForTest(ABC.class)
public class ABCTest {

    @Test
    public void finalCouldBeMock() {
        final ABC abc = PowerMockito.mock(ABC.class);
        PowerMockito.when(abc.myMethod()).thenReturn("toto");
        assertEquals("toto", abc.myMethod());
    }
}

0
投票
    @PrepareForTest(Demo.class)
    public class DemoTest {

        @Rule
        public powerMockRule = new PowerMockRule()

        @Before
        public void setup(){
        PowerMockAgent.initializeIfNeeded();
        }
        @Test
        public void finalClassMock() {
            final Demo demo = PowerMockito.mock(Demo.class);
            PowerMockito.when(demo.myMethod()).thenReturn("something");
            assertEquals("something", demo.myMethod());
        }
    }

或者这种方式也有效,谢谢

@gontard

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