Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Final method mocking

I need mock some class with final method using mockito. I have wrote something like this

@Test public void test() {     B b = mock(B.class);     doReturn("bar called").when(b).bar();        assertEquals("must be \"overrided\"", "bar called", b.bar());     //bla-bla }   class B {     public final String bar() {         return "fail";     } } 

But it fails. I tried some "hack" and it works.

   @Test    public void hackTest() {         class NewB extends B {             public String barForTest() {                 return bar();             }         }         NewB b = mock(NewB.class);         doReturn("bar called").when(b).barForTest();         assertEquals("must be \"overrided\"", "bar called", b.barForTest());     } 

It works, but "smells".

So, Where is the right way?

Thanks.

like image 466
Stan Kurilin Avatar asked Sep 25 '10 12:09

Stan Kurilin


People also ask

Can final method be mocked?

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.

Can a final class be mocked?

You cannot mock a final class with Mockito, as you can't do it by yourself.

What is method mocking?

Mocking is done when you invoke methods of a class that has external communication like database calls or rest calls. Through mocking you can explicitly define the return value of methods without actually executing the steps of the method.


2 Answers

From the Mockito FAQ:

What are the limitations of Mockito

  • Cannot mock final methods - their real behavior is executed without any exception. Mockito cannot warn you about mocking final methods so be vigilant.
like image 73
matt b Avatar answered Oct 27 '22 00:10

matt b


There is no support for mocking final methods in Mockito.

As Jon Skeet commented you should be looking for a way to avoid the dependency on the final method. That said, there are some ways out through bytecode manipulation (e.g. with PowerMock)

A comparison between Mockito and PowerMock will explain things in detail.

like image 28
iwein Avatar answered Oct 27 '22 01:10

iwein