sura watthana
sura watthana

Reputation: 291

Can Powermockito mock final method in non-final concrete class?

Let's say I have a non-final concrete class with a final method like the one below.

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

is it possible to mock myMethod() to return something else when it is called in junit using Powermockito? Thank you

Upvotes: 17

Views: 30024

Answers (2)

arvindsis11
arvindsis11

Reputation: 1

    @PrepareForTest(Demo.class)
    public class DemoTest {

        @Rule
        public PowerMockRule rule = 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());
        }
    }

or this way also works thanks @gontard

Upvotes: 0

gontard
gontard

Reputation: 29550

This works :

@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());
    }
}

Upvotes: 32

Related Questions