Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 513
sura watthana Avatar asked Aug 27 '12 09:08

sura watthana


People also ask

Can a final method be mocked?

Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.

Can we mock private methods using PowerMockito?

PowerMock integrates with mocking frameworks like EasyMock and Mockito and is meant to add additional functionality to these – such as mocking private methods, final classes, and final methods, etc. It does that by relying on bytecode manipulation and an entirely separate classloader.

What is the difference between Mockito and PowerMockito?

While Mockito can help with test case writing, there are certain things it cannot do viz:. mocking or testing private, final or static methods. That is where, PowerMockito comes to the rescue. PowerMockito is capable of testing private, final or static methods as it makes use of Java Reflection API.

Can we test final classes and primitive types using Mockito?

Configure Mockito for Final Methods and ClassesBefore we can use Mockito for mocking final classes and methods, we have to configure it. Mockito checks the extensions directory for configuration files when it is loaded. This file enables the mocking of final methods and classes.


1 Answers

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());
    }
}
like image 176
gontard Avatar answered Sep 27 '22 21:09

gontard